2013-07-17 6 views
3

В моем приложении я хочу создать страницу с расширениемListView и под ним CheckBox.ExpandableListView внутри scrollview

Моя проблема в том, что мой ExpandableListView слишком велик и сделать CheckBox на странице.

На небольших экранах не видно вообще.

Я попытался установить ExpandableListView внутри scrollview, но не работал.

Есть ли способ сделать мой дизайн?

Это мой код и скриншот.

код XML:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="@color/White" > 

    <ScrollView 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:fillViewport="true" > 

     <RelativeLayout 
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent" > 

      <TextView 
       android:id="@+id/textView1" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_alignParentTop="true" 
       android:layout_marginTop="15sp" 
       android:text="In this page you can save a group of exercise under one routine." 
       android:textColor="@color/Black" 
       android:textSize="20sp" /> 

      <ExpandableListView 
       android:id="@+id/instructionsExView" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_alignParentLeft="true" 
       android:layout_below="@+id/textView1" 
       android:layout_marginTop="15sp" > 
      </ExpandableListView> 

      <TextView 
       android:id="@+id/textView2" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_below="@+id/instructionsExView" 
       android:layout_marginTop="15sp" 
       android:text="If you want to open the instruction again check &apos;need help?&apos;" 
       android:textColor="@color/Black" 
       android:textSize="20sp" /> 

      <CheckBox 
       android:id="@+id/checkInstructions" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_alignParentLeft="true" 
       android:layout_below="@+id/textView2" 
       android:layout_marginTop="16dp" 
       android:checked="false" 
       android:text="dont show again when opening the page" 
       android:textColor="@color/Black" /> 

     </RelativeLayout> 
    </ScrollView> 

</RelativeLayout> 

Снимок экрана:

enter image description here

EDIT:

enter image description here

+0

Использовать 'MergeAdapter': https://github.com/commonsguy/cwac-merge – gunar

ответ

1

вы наклоняю использовать ListView вид внутри прокрутки, так что вы должны использовать прокрутки просматривать и добавлять строки в виде представлений динамически.

1

Вам не нужно больше одного RelativeLayout, так как expandablelistview должно быть между двумя элементами (в вашем случае), эти два элемента будут первыми с parentTop и parentBottom, остальные будут позиционироваться, играя с выше/ниже.

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:background="@color/White" 
android:orientation="vertical" > 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:layout_marginTop="15sp" 
    android:text="In this page you can save a group of exercise under one routine." 
    android:textColor="@color/Black" 
    android:textSize="20sp" /> 

<CheckBox 
    android:id="@+id/checkInstructions" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentBottom="true" 
    android:layout_marginTop="16dp" 
    android:checked="false" 
    android:text="dont show again when opening the page" 
    android:textColor="@color/Black" /> 

<TextView 
    android:id="@+id/textView2" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_above="@+id/checkInstructions" 
    android:layout_marginTop="15sp" 
    android:text="If you want to open the instruction again check &apos;need help?&apos;" 
    android:textColor="@color/Black" 
    android:textSize="20sp" /> 

<ExpandableListView 
    android:id="@+id/instructionsExView" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_above="@+id/textView2" 
    android:layout_below="@id/textView1" 
    android:layout_marginTop="15sp" > 
</ExpandableListView> 

</RelativeLayout> 
+0

, но я хочу, чтобы мой флажок был ниже ExpandableListView – dasdasd

+0

И это, посмотрите на parentBottom внутри флажка. Следующие элементы будут окрашены с учетом флажка, посмотрите атрибуты следующих элементов. Поскольку вы видите ExpandableListView последним, это не значит, что это последний, который будет показан на экране. – AlexBcn

+0

Это своего рода работа. Поскольку ExpandableListView теперь расширяется только в маленькой области. Я хочу, чтобы он расширялся до размера экрана. Смотрите мое редактирование и снимок экрана. – dasdasd

0

Для достижения этой цели вы можете использовать нижеследующий код. Я использовал ListView вы можете заменить ExpandableListView

<?xml version="1.0" encoding="utf-8"?> 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:layout_marginTop="15sp" 
    android:text="In this page you can save a group of exercise under one routine." 
    android:textColor="@color/WHITE" 
    android:textSize="20sp" /> 

<ListView 
    android:id="@+id/listView1" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_weight="2" > 

</ListView> 

<TextView 
    android:id="@+id/textView2" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_marginTop="15sp" 
    android:text="If you want to open the instruction again check &apos;need help?&apos;" 
    android:textColor="@color/WHITE" 
    android:textSize="20sp" /> 

<CheckBox 
    android:id="@+id/checkInstructions" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignParentLeft="true" 
    android:layout_below="@+id/textView2" 
    android:layout_marginBottom="20dp" 
    android:layout_marginTop="16dp" 
    android:checked="false" 
    android:text="dont show again when opening the page" 
    android:textColor="@color/WHITE" /> 

Я проверил код выше приблизительно с 50 значением ListItem и протестирована на очень маленьком устройстве отображения и она отлично работает.

<?xml version="1.0" encoding="utf-8"?> 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:layout_marginTop="15sp" 
    android:text="In this page you can save a group of exercise under one routine." 
    android:textColor="@color/WHITE" 
    android:textSize="20sp" /> 

<ExpandableListView 
    android:id="@+id/expandableListView1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_weight="2" > 

</ExpandableListView> 

<TextView 
    android:id="@+id/textView2" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_marginTop="15sp" 
    android:text="If you want to open the instruction again check &apos;need help?&apos;" 
    android:textColor="@color/WHITE" 
    android:textSize="20sp" /> 

<CheckBox 
    android:id="@+id/checkInstructions" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignParentLeft="true" 
    android:layout_below="@+id/textView2" 
    android:layout_marginBottom="20dp" 
    android:layout_marginTop="16dp" 
    android:checked="false" 
    android:text="dont show again when opening the page" 
    android:textColor="@color/WHITE" /> 

Я проверил с ExpandableListView и работает нормально для меня.

+1

Не работает. ExpandableListView не будет расширяться. – dasdasd

+0

http://stackoverflow.com/questions/34269075/scrollview-not-working-androidinside-the-scrollview-i-have-a-expandable-listvie ссылается на эту ссылку и дает решение, пожалуйста, @dasdasd – YUVRAJ

17

в вашем "OnCreate" метод записи: "setListViewHeight (expListView)" после "expListView.setAdapter (listAdapter)", а затем установить OnGroupClickListener для расширяемой виде списка, как показано ниже:

expListView.setOnGroupClickListener(new OnGroupClickListener() { 

     @Override 
     public boolean onGroupClick(ExpandableListView parent, View v, 
       int groupPosition, long id) { 
      setListViewHeight(parent, groupPosition); 
      return false; 
     } 
    }); 

используемых методов:

private void setListViewHeight(ListView listView) { 
    ListAdapter listAdapter = listView.getAdapter(); 
    int totalHeight = 0; 
    for (int i = 0; i < listAdapter.getCount(); i++) { 
    View listItem = listAdapter.getView(i, null, listView); 
    listItem.measure(0, 0); 
    totalHeight += listItem.getMeasuredHeight(); 
    } 

    ViewGroup.LayoutParams params = listView.getLayoutParams(); 
    params.height = totalHeight 
    + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); 
    listView.setLayoutParams(params); 
    listView.requestLayout(); 
    } 


    private void setListViewHeight(ExpandableListView listView, 
    int group) { 
    ExpandableListAdapter listAdapter = (ExpandableListAdapter) listView.getExpandableListAdapter(); 
    int totalHeight = 0; 
    int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), 
    MeasureSpec.EXACTLY); 
    for (int i = 0; i < listAdapter.getGroupCount(); i++) { 
    View groupItem = listAdapter.getGroupView(i, false, null, listView); 
    groupItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED); 

    totalHeight += groupItem.getMeasuredHeight(); 

    if (((listView.isGroupExpanded(i)) && (i != group)) 
    || ((!listView.isGroupExpanded(i)) && (i == group))) { 
    for (int j = 0; j < listAdapter.getChildrenCount(i); j++) { 
    View listItem = listAdapter.getChildView(i, j, false, null, 
    listView); 
    listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED); 

    totalHeight += listItem.getMeasuredHeight(); 

    } 
    } 
    } 

    ViewGroup.LayoutParams params = listView.getLayoutParams(); 
    int height = totalHeight 
    + (listView.getDividerHeight() * (listAdapter.getGroupCount() - 1)); 
    if (height < 10) 
    height = 200; 
    params.height = height; 
    listView.setLayoutParams(params); 
    listView.requestLayout(); 

    } 

Теперь у вас хорошо.

+0

Это очень хорошо работает для me ... Однако, когда ExpandableListView прокручивается вверх и выходит из зоны просмотра, список автоматически сбрасывается. Что может быть решением этого? Я использую _setListViewHeight (метод ExpandableListView ..._ – user1036908

+0

Этот код полезен, когда ExpandableListView должен иметь атрибут layout_height = "wrap_content". С кодом вашего представления будет завершен контент. – Sniper

+0

Вторая функция работает нормально, но первая один из них не работает для меня, то есть до того, как будет нажата любая группа, высота списка expandablelistview неверна. Кто-нибудь смог это решить? – dvc

6

Основано на @Dmila Ram `s answer, я был в состоянии сделать это.

В моем случае, я инициализировать и заполнить ExpandableListView в методе onCreate так:

expandableListView = (ExpandableListView) findViewById(R.id.appsMenu); 
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild); 
expandableListView.setAdapter(listAdapter); 
for (int i = 0; i < listAdapter.getGroupCount(); i++) 
    expandableListView.expandGroup(i); 
setListViewHeight(expandableListView); 
expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { 
    @Override 
    public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { 
      setListViewHeight(parent, groupPosition); 
      return false; 
     } 
    }); 

Обратите внимание, что я расширяю каждую группу. После этого я звоню setListViewHeight(expandableListView);

Этот метод отвечает за вычисление высоты ExpandableListView при его создании в первый раз.

Вот код:

private void setListViewHeight(ExpandableListView listView) { 
     ExpandableListAdapter listAdapter = (ExpandableListAdapter) listView.getExpandableListAdapter(); 
     int totalHeight = 0; 
     for (int i = 0; i < listAdapter.getGroupCount(); i++) { 
      View groupView = listAdapter.getGroupView(i, true, null, listView); 
      groupView.measure(0, View.MeasureSpec.UNSPECIFIED); 
      totalHeight += groupView.getMeasuredHeight(); 

     if (listView.isGroupExpanded(i)){ 
      for(int j = 0; j < listAdapter.getChildrenCount(i); j++){ 
       View listItem = listAdapter.getChildView(i, j, false, null, listView); 
       listItem.measure(0, View.MeasureSpec.UNSPECIFIED); 
       totalHeight += listItem.getMeasuredHeight(); 
      } 
     } 
    } 

    ViewGroup.LayoutParams params = listView.getLayoutParams(); 
    params.height = totalHeight 
      + (listView.getDividerHeight() * (listAdapter.getGroupCount() - 1)); 
    listView.setLayoutParams(params); 
    listView.requestLayout(); 
} 

Это действительно не нужно иметь группы расширяется, вместо этого мы можем просто перебрать дочерние элементы и добавить их в расчете на общую высоту.

Это сделает все виджеты в прокручиваемом ScrollView, и он также отобразит ExpandableListView должным образом.

Тогда мы также нужен этот метод, чтобы убедиться, что при нажатии на группы будет рассчитать высоту, а также:

private void setListViewHeight(ExpandableListView listView, 
            int group) { 
     ExpandableListAdapter listAdapter = (ExpandableListAdapter) listView.getExpandableListAdapter(); 
     int totalHeight = 0; 
     int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), 
       View.MeasureSpec.EXACTLY); 
     for (int i = 0; i < listAdapter.getGroupCount(); i++) { 
      View groupItem = listAdapter.getGroupView(i, false, null, listView); 
     groupItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED); 
     totalHeight += groupItem.getMeasuredHeight(); 

     if (((listView.isGroupExpanded(i)) && (i != group)) 
       || ((!listView.isGroupExpanded(i)) && (i == group))) { 
      for (int j = 0; j < listAdapter.getChildrenCount(i); j++) { 
       View listItem = listAdapter.getChildView(i, j, false, null, 
         listView); 
       listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED); 
       totalHeight += listItem.getMeasuredHeight(); 
      } 
     } 
    } 

    ViewGroup.LayoutParams params = listView.getLayoutParams(); 
    int height = totalHeight 
      + (listView.getDividerHeight() * (listAdapter.getGroupCount() - 1)); 
    if (height < 10) 
     height = 200; 
    params.height = height; 
    listView.setLayoutParams(params); 
    listView.requestLayout(); 
} 

Это в значительной степени это, то он работает нормально, но это решение может быть оптимизирована даже в дальнейшем.

+0

Nice.It очень полезно и точно. –