ExpandableLists in Android, I want to allow only one parent list to expand at a time

后端 未结 8 1679
难免孤独
难免孤独 2021-02-04 17:15

I want to make only one item in the parent list expand at a time, my code for the onCreate is currently the following. (It works as I want, But the method to allow only one pare

8条回答
  •  长发绾君心
    2021-02-04 17:43

    I believe a straight forward solution would be to implement one Adapter to handle any of the events you are interested in.

    public class MyExpandableListAdapter extends SimpleExpandableListAdapter {
    
      public Activity mActivity;
    
      public MyExpandableListAdapter([ARGS USED IN QUESTION], Activity activity) {super([ARGS USED IN QUESTIONS]); mActivity = activity; }
    
      // then just override the method
      public void onGroupExpanded(int groupPosition) {
        int len = super.getGroupCount();
        ExpandableListView list = (ExpandableListView) mActivity.findViewById(R.id.list);
        for (int i = 0; i < len; i++) {
            if (i != groupPosition) {
                list.collapseGroup(i);
            }
        }
      }
    }
    

    By separating the list adapter into another class you will not clutter the Activity code with one-off listener implementations. Instead, in each Activity simply instantiate the adapter and set it on the list

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        // No try catch needed
        MyExpandableListAdapter mAdapter = new MyExpandableListAdapter([ARGS SHOWN IN QUESTION], MainActivity.this);
    
        ExpandableListView epView = (ExpandableListView) findViewById(R.id.list);
        epView.setAdapter(mAdapter);
    
        return true;
    }
    

提交回复
热议问题