2015-12-04 3 views
1

Раньше я использовал LinearLayout для моих родительских и дочерних взглядов, и я их расширить, используя ниже кода sniplet в по щелчку развертываемых родительского списка:ExpandableList не расширяется внутри ScrollView

subtask_explist.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { 

     @Override 
     public boolean onGroupClick(ExpandableListView parent, View v, 
            int groupPosition, long id) { 
      Log.d("subtask_explist" , " pressed"); 
      setListViewHeight(parent, groupPosition); 
      return false; 
     } 
    }); 

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(); 

} 

Старой раскладка являются:

child_row_ad_subtask.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
android:id="@+id/LinearLayout01" 
android:layout_width="fill_parent" 
android:layout_height="56dp" 
android:background="@color/white_color" 
xmlns:android="http://schemas.android.com/apk/res/android"> 

<CheckBox 
    android:layout_width="wrap_content" 
    android:layout_height="56dp" 
    android:layout_gravity="center_vertical" 
    android:layout_marginRight="5dp" 
    android:layout_marginLeft="10dp" 
    android:focusable="false" 
    android:id="@+id/cb_subtask" /> 

<TextView 
    android:id="@+id/tv_subtask" 
    android:layout_width="wrap_content" 
    android:layout_height="56dp" 
    android:layout_marginLeft="5dp" 
    android:layout_gravity="center_vertical" 
    android:text="Single-line item" 
    android:gravity="center_vertical" 
    android:paddingLeft="5dip" 
    android:textColor="#000000" 
    android:textStyle="normal" 
    android:textSize="17dip" 
    android:clickable="false"> 
</TextView> 
</LinearLayout> 

и теперь я обновил свой код и изменить корневой макет "LinearLayout" в "Relative Layout":

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:paddingLeft="16dp" 
android:paddingRight="16dp" 
android:layout_width="match_parent" 
android:layout_height="56dp" 
android:background="@color/white_color" 
android:id="@+id/LinearLayout01"> 

<RelativeLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
<LinearLayout 
    android:layout_width="wrap_content" 
    android:layout_height="match_parent"> 

    <android.support.v7.widget.AppCompatCheckBox 
      android:id="@+id/cb_subtask" 
      android:layout_gravity="center_vertical" 
      android:focusable="false" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"/> 
</LinearLayout> 
    <android.support.v7.widget.AppCompatTextView 
     android:id="@+id/tv_subtask" 
     android:paddingLeft="56dp" 
     android:paddingTop="17dp" 
     android:textSize="16sp" 
     android:paddingBottom="20dp" 
     android:textColor="#000000" 
     android:clickable="false" 
     android:text="Single Line Item " 
     android:layout_width="wrap_content" 
     android:layout_height="56dp" 
     /> 

</RelativeLayout> 
</LinearLayout> 

Теперь тот же метод setListViewHeight (parent, groupPosition); не работает, что дает ошибку:

FATAL EXCEPTION: main java.lang.NullPointerException 
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:500) 
at android.view.View.measure(View.java:15349) 
at com.ujjawal.test.testdesignapplication.MainActivity.setListViewHeight(MainActivity.java:227) 
at com.ujjawal.test.testdesignapplication.MainActivity.access$000(MainActivity.java:21) 
at com.ujjawal.test.testdesignapplication.MainActivity$2.onGroupClick(MainActivity.java:126) 
at android.widget.ExpandableListView.handleItemClick(ExpandableListView.java:561) 
at android.widget.ExpandableListView.performItemClick(ExpandableListView.java:539) 
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2859) 
at android.widget.AbsListView$1.run(AbsListView.java:3533) 
at android.os.Handler.handleCallback(Handler.java:615) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4802) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:813) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:580) 
at dalvik.system.NativeStart.main(Native Method) 

У меня есть 3 расширяемый список один ниже другого в одном макете, если я удалю Scrollview все работает нормально, но без Scrollview по расширению списка других списков ниже, выходит из экрана.

Я хочу иметь все 3 списка с расширяющимся поведением.

Заранее спасибо :)

+0

Все группы имеют детей не так ли? убедитесь, что у вас есть правильная обработка для getChildCount в адаптере. Btw, которая является номером 227 в основной деятельности? –

+0

В этом расширяемом списке есть только одна группа и содержит детей @Override public int getChildrenCount (int groupPosition) { return childItems.size(); } Номер строки 227 в основной деятельности: группаItem.measure (желательноWidth, View.MeasureSpec.UNSPECIFIED); в способе, который я изложил в описании. Thanx для ответа :) Ожидание точного ответа ... – Ujjawal

ответ

1
View groupItem = listAdapter.getGroupView(i, false, null, listView); 

//here you may be getting groupItem as null. Before calling anyMethod on groupItem you needs to add a null check 

if(groupItem!=null) 
{ 
groupItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED); 
} 
// This is one solution. But we need to identify listAdapter.getGroupView(i, false, null, listView); why this call is returning null. can you post your getGroupView method of the adapter ? 

Update ставить нулевую проверку на overlall код, как этот

for (int i = 0; i < listAdapter.getGroupCount(); i++) { 
      View groupItem = listAdapter.getGroupView(i, false, null, listView); 
      if(groupItem!=null) 
    { 
      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); 
if(listItem!=null) 
{ 
        listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED); 

        totalHeight += listItem.getMeasuredHeight(); 

}    } 
      } 
    } 
+0

Теперь же он показывает исключения нулевого указателя к неустранимым: главный java.lang.NullPointerException в android.widget.RelativeLayout.onMeasure (RelativeLayout.java : 500) на android.view.View.measure (View.java:15349) at com.ujjawal.test.testdesignapplication.MainActivity.setListViewHeight (MainActivity.java:230) – Ujjawal

+0

Отладить и посмотреть, какой объект имеет значение null. Положите точку останова на строку, где вы получаете ошибку и проверьте –

+0

Привет, Нитиш. Я могу отправить вам мой код, можете ли вы поделиться мне своим почтовым идентификатором? – Ujjawal

Смежные вопросы