zoukankan      html  css  js  c++  java
  • Android ExpandableListView的使用

    Android ExpandableListView的使用

    一、MainActivity要继承ExpandableListActivity。效果是当单机ListView的子项是显示另一个ListView。

    public class MainActivity extends ExpandableListActivity {
    	
    	private static final String NAME = "NAME";
    	private static final String IS_EVEN = "IS_EVEN";
    	private ExpandableListAdapter eListAdapter;
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		
    		List<Map<String,String>> groupData = new ArrayList<Map<String,String>>();
    		List<List<Map<String, String>>> childDataList = new ArrayList<List<Map<String,String>>>();
    		for (int i = 0; i < 10; i++) {
    			Map<String, String> curGroupMap = new HashMap<String, String>();
    			groupData.add(curGroupMap);
    			curGroupMap.put(NAME, "Group"+i);
    			curGroupMap.put(IS_EVEN, (i%2==0)? "This group is even": "This group is odd");
    			
    			List<Map<String, String>> children = new ArrayList<Map<String,String>>();
    			for (int j = 0; j < 8; j++) {
    				Map<String, String> curChildMap = new HashMap<String, String>();
    				children.add(curChildMap);
    				curChildMap.put(NAME, "Child" + j);
    				curChildMap.put(IS_EVEN, (j % 2 == 0) ? "This child is even" : "This child is odd" );
    			}
    			childDataList.add(children);
    		}
    		eListAdapter = new SimpleExpandableListAdapter(
    				this, 
    				groupData, 
    				android.R.layout.simple_expandable_list_item_2,
    				new String[] {NAME, IS_EVEN }, 
    				new int[] { android.R.id.text1, android.R.id.text2}, 
    				childDataList, 
    				android.R.layout.simple_expandable_list_item_2, 
    				new String[] {NAME, IS_EVEN}, 
    				new int[] { android.R.id.text1, android.R.id.text2});
    		
    		setListAdapter(eListAdapter);
    				
    	}
    }
    

    代码解释

    1、groupData是父数据 ,childDataList是子数据。

    2、android.R.layout.simple_expandable_list_item_2表示list的实现方式

    3、new String[] { NAME,IS_EVEN}list需要显示的数据。             

    效果图:

    也就是单机Group2时,显示Group2的数据。

    二、数据源:SimpleCursorTreeAdapter的使用

    显示通讯录中的姓名,单击用姓名,显示号码。前提还要分配读取通讯录的权限

     <uses-permission android:name="android.permission.READ_CONTACTS"/>
    

     代码如下:

    public class ExpandableList2 extends ExpandableListActivity {  
        private int mGroupIdColumnIndex;   
          
        private String mPhoneNumberProjection[] = new String[] {  
                People.Phones._ID, People.Phones.NUMBER  
        };  
      
          
        private ExpandableListAdapter mAdapter;  
          
    
        @Override  
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
      
            // Query for people  
            Cursor groupCursor = managedQuery(People.CONTENT_URI,  
                    new String[] {People._ID, People.NAME}, null, null, null);  
      
            // Cache the ID column index  
            mGroupIdColumnIndex = groupCursor.getColumnIndexOrThrow(People._ID);  
      
            // Set up our adapter  
            mAdapter = new MyExpandableListAdapter(groupCursor,  
                    this,  
                    android.R.layout.simple_expandable_list_item_1,  
                   android.R.layout.simple_expandable_list_item_1,  
                    new String[] {People.NAME}, // Name for group layouts  
                    new int[] {android.R.id.text1},  
                    new String[] {People.NUMBER}, // Number for child layouts  
                    new int[] {android.R.id.text1});  
            setListAdapter(mAdapter);  
        }  
      
        public class MyExpandableListAdapter extends SimpleCursorTreeAdapter {  
      
            public MyExpandableListAdapter(Cursor cursor, Context context, int groupLayout,  
                    int childLayout, String[] groupFrom, int[] groupTo, String[] childrenFrom,  
                    int[] childrenTo) {  
                super(context, cursor, groupLayout, groupFrom, groupTo, childLayout, childrenFrom,  
                        childrenTo);  
            }  
      
      
            @Override  
            protected Cursor getChildrenCursor(Cursor groupCursor) {  
                // Given the group, we return a cursor for all the children within that group   
      
                // Return a cursor that points to this contact's phone numbers  
                Uri.Builder builder = People.CONTENT_URI.buildUpon();  
                ContentUris.appendId(builder, groupCursor.getLong(mGroupIdColumnIndex));  
                builder.appendEncodedPath(People.Phones.CONTENT_DIRECTORY);  
                Uri phoneNumbersUri = builder.build();  
      
                // The returned Cursor MUST be managed by us, so we use Activity's helper  
                // functionality to manage it for us.  
                return managedQuery(phoneNumbersUri, mPhoneNumberProjection, null, null, null);  
            }  
      
        }  
    

     三、通过BaseExpandableListAdapter绑定数据

    1.BaseExpandableListAdapter

    public class ExpandableList3 extends Activity {  
      
    	private String[] groups = { "group1", "group2", "group3", "group4" };  
        private String[][] children = {  
                { "g1 item1", "g1 item2", "g1 item3", "g1 item4" },  
                { "g2 item1", "g2 item2", "g2 item3", "g2 item4" },  
                { "g3 item1", "g3 item2" },  
                { "g4 item1", "g4 item2" }  
        };  
        //ExpandableListAdapter mAdapter;  
        private ExpandableListView expandableListView;
        private TextView tView = null; 
    	
        @Override  
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
      
            setContentView(R.layout.activity_main);
            
            tView = (TextView)findViewById(R.id.textView1);
            expandableListView = (ExpandableListView)findViewById(R.id.expandableListView1);
            
            ExpandableListAdapter adapter = new BaseExpandableListAdapter() {
       	
    			@Override
    			public boolean isChildSelectable(int groupPosition, int childPosition) {
    				// TODO Auto-generated method stub
    				String string = groups[groupPosition] + children[groupPosition][childPosition];
    				tView.setText(string);
    				return true;
    			}
    			
    			@Override
    			public boolean hasStableIds() {
    				// TODO Auto-generated method stub
    				return true;
    			}
    			
    			@Override
    			public View getGroupView(int groupPosition, boolean isExpanded,
    					View convertView, ViewGroup parent) {
    				// TODO Auto-generated method stub
    				LinearLayout layout = new LinearLayout(ExpandableList3.this);
    				layout.setOrientation(0);
    				layout.setPadding(50, 0, 0, 0);
    				ImageView imageView = new ImageView(ExpandableList3.this);
    				imageView.setImageResource(R.drawable.ic_launcher);
    				layout.addView(imageView);
    				
    				TextView textView = getTextView();
    				textView.setText(getGroup(groupPosition).toString());
    				layout.addView(textView);
    				return layout;
    			}
    			
    			private TextView getTextView() {
    				// TODO Auto-generated method stub
    				AbsListView.LayoutParams lParams = new AbsListView.LayoutParams(
    						ViewGroup.LayoutParams.FILL_PARENT, 64);
    				TextView textView = new TextView(ExpandableList3.this);
    				textView.setLayoutParams(lParams);
    				textView.setPadding(20, 0, 0, 0);
    				textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
    				return textView;
    			}
    
    			@Override
    			public long getGroupId(int groupPosition) {
    				// TODO Auto-generated method stub
    				return groupPosition;
    			}
    			
    			@Override
    			public int getGroupCount() {
    				// TODO Auto-generated method stub
    				return groups.length;
    			}
    			
    			@Override
    			public Object getGroup(int groupPosition) {
    				// TODO Auto-generated method stub
    				return groups[groupPosition];
    			}
    			
    			@Override
    			public int getChildrenCount(int groupPosition) {
    				// TODO Auto-generated method stub
    				return children[groupPosition].length;
    			}
    			
    			@Override
    			public View getChildView(int groupPosition, int childPosition,
    					boolean isLastChild, View convertView, ViewGroup parent) {
    				// TODO Auto-generated method stub
    				TextView textView  = getTextView();
    				textView.setText(getChild(groupPosition, childPosition).toString());
    				return textView;
    			}
    			
    			@Override
    			public long getChildId(int groupPosition, int childPosition) {
    				// TODO Auto-generated method stub
    				return childPosition;
    			}
    			
    			@Override
    			public Object getChild(int groupPosition, int childPosition) {
    				// TODO Auto-generated method stub
    				return children[groupPosition][childPosition];
    			}
    			
    			
    		};
       
    		expandableListView.setAdapter(adapter);
        }  
          
    }
    

     效果图:点击子项时,显示子项的信息。

    2.数据源写一个类MyExpandableListAdapter,该类继承自 BaseExpandableListAdapter。

    public class ExpandableList1 extends ExpandableListActivity {  
      
        ExpandableListAdapter mAdapter;  
      
        @Override  
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
      
            // Set up our adapter  
            mAdapter = new MyExpandableListAdapter();  
            setListAdapter(mAdapter);  
            // register context menu, when long click the item, it will show a dialog  
            registerForContextMenu(getExpandableListView());  
        }  
          
        @Override  
        public boolean onContextItemSelected(MenuItem item) {  
            ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item.getMenuInfo();  
      
            String title = ((TextView) info.targetView).getText().toString();  
              
            int type = ExpandableListView.getPackedPositionType(info.packedPosition);  
            if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {  
                int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);   
                int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);   
                Toast.makeText(this, title + ": Child " + childPos + " clicked in group " + groupPos,  
                        Toast.LENGTH_SHORT).show();  
                return true;  
            } else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {  
                int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);   
                Toast.makeText(this, title + ": Group " + groupPos + " clicked", Toast.LENGTH_SHORT).show();  
                return true;  
            }  
              
            return false;  
        }  
      
        /** 
         * A simple adapter which maintains an ArrayList of photo resource Ids.  
         * Each photo is displayed as an image. This adapter supports clearing the 
         * list of photos and adding a new photo. 
         * 
         */  
        public class MyExpandableListAdapter extends BaseExpandableListAdapter {  
            // Sample data set.  children[i] contains the children (String[]) for groups[i].  
            private String[] groups = { "People Names", "Dog Names", "Cat Names", "Fish Names" };  
            private String[][] children = {  
                    { "Arnold", "Barry", "Chuck", "David" },  
                    { "Ace", "Bandit", "Cha-Cha", "Deuce" },  
                    { "Fluffy", "Snuggles" },  
                    { "Goldy", "Bubbles" }  
            };  
              
            public Object getChild(int groupPosition, int childPosition) {  
                return children[groupPosition][childPosition];  
            }  
      
            public long getChildId(int groupPosition, int childPosition) {  
                return childPosition;  
            }  
      
            public int getChildrenCount(int groupPosition) {  
                return children[groupPosition].length;  
            }  
      
            public TextView getGenericView() {  
                // Layout parameters for the ExpandableListView  
                AbsListView.LayoutParams lp = new AbsListView.LayoutParams(  
                        ViewGroup.LayoutParams.FILL_PARENT, 64);  
      
                TextView textView = new TextView(ExpandableList1.this);  
                textView.setLayoutParams(lp);  
                // Center the text vertically  
                textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);  
                // Set the text starting position  
                textView.setPadding(36, 0, 0, 0);  
                return textView;  
            }  
              
            public View getChildView(int groupPosition, int childPosition, boolean isLastChild,  
                    View convertView, ViewGroup parent) {  
                TextView textView = getGenericView();  
                textView.setText(getChild(groupPosition, childPosition).toString());  
                return textView;  
           }  
     
            public Object getGroup(int groupPosition) {  
                return groups[groupPosition];  
            }  
      
           public int getGroupCount() {  
               return groups.length;  
           }  
     
            public long getGroupId(int groupPosition) {  
                return groupPosition;  
            }  
      
           public View getGroupView(int groupPosition, boolean isExpanded, View convertView,  
                   ViewGroup parent) {  
               TextView textView = getGenericView();  
                textView.setText(getGroup(groupPosition).toString());  
                return textView;  
            }  
      
          public boolean isChildSelectable(int groupPosition, int childPosition) {  
                return true;  
            }  
     
            public boolean hasStableIds() {  
               return true;  
            }  
      
        }  
    } 
    

     效果图:

    作者:Work Hard Work Smart
    出处:http://www.cnblogs.com/linlf03/
    欢迎任何形式的转载,未经作者同意,请保留此段声明!

  • 相关阅读:
    交换机技术
    第七周课后总结
    以太网原理
    test
    NetCore第一步:千里之行 始于环境构筑
    第二十课(一)
    第十九课(三)
    第十九课(二)
    第十九课(一)
    第十八课(三)
  • 原文地址:https://www.cnblogs.com/linlf03/p/2980293.html
Copyright © 2011-2022 走看看