UI组件之AdapterView及其子类(六)ExpandableListView组件和ExpandableListActivity的使用
ExpandableListView是ListView的子類,他在ListView上進(jìn)行了擴(kuò)展,它把列表項分成了幾組,每組里包含了多個列表項
ExpandableListView的列表項是由ExpandableListAdapter提供的,實現(xiàn)ExpandableListAdapter三種常用方式,常用的ExpandableListAdapter子類如下:
1,擴(kuò)展BaseExpandableListAdapter實現(xiàn)ExpandableListAdapter
2,使用SimpleExpandableListAdapter將 兩個List集合包裝成ExpandableListAdapter
3,使用SimpleCursorTreeAdapter將Cursor中的數(shù)據(jù)包裝成SimpleCursorTreeAdapter
ExpandableListAdapter及其子類的繼承關(guān)系類圖看這篇文章講的比較好,看懂了:http://hubingforever.blog.163.com/blog/static/1710405792010538823477/
ExpandableListView的xml屬性:
? ? ?android:childDivider 指定個組內(nèi)各子列表項之間的分隔條
? ? ?android:childIndicator 顯示子列表項旁邊的Drawble對象
? ? ?android:groupIndicator 顯示組列表項旁邊的Drawble對象
ExpandableListView是android中可以實現(xiàn)下拉list的一個控件,是一個垂直滾動的心事兩個級別列表項手風(fēng)琴試圖,列表項是來自ExpandableListViewaAdapter,組可以單獨展開。
重要方法:
<span style="font-size:24px;">expandGroup (int groupPos) ;//在分組列表視圖中 展開一組, setSelectedGroup (int groupPosition) ;//設(shè)置選擇指定的組。 setSelectedChild (int groupPosition, int childPosition, boolean shouldExpandGroup);//設(shè)置選擇指定的子項。 getPackedPositionGroup (long packedPosition);//返回所選擇的組 getPackedPositionForChild (int groupPosition, int childPosition) ;//返回所選擇的子項 getPackedPositionType (long packedPosition);//返回所選擇項的類型(Child,Group) isGroupExpanded (int groupPosition);//判斷此組是否展開</span> <span style="font-size:24px;">expandableListView.setDivider();這個是設(shè)定每個Group之間的分割線。 expandableListView.setGroupIndicator();這個是設(shè)定每個Group之前的那個圖標(biāo)。 expandableListView.collapseGroup(int group); 將第group組收起</span>
一,使用擴(kuò)展BaseExpandableListAdapter來提供數(shù)據(jù)源
擴(kuò)展BaseExpandableListAdapter需要重寫11個方法:
?? ? ?* getGroupCount(),返回包含組列表的數(shù)量
? ? ? ? ? ? ?* getChildrenCount(int groupPosition),返回包含組列表的數(shù)量
? ? ? ? ? ? ?*?
? ? ? ? ? ? ?* getGroup(int groupPosition),返回組列表的對象
? ? ? ? ? ? ?* getChild(int groupPosition, int childPosition),返回組列表下的子列表對象
? ? ? ? ? ? ?*?
? ? ? ? ? ? ?* getGroupId(int groupPosition),返回組列表Id
? ? ? ? ? ? ?* getChildId(int groupPosition, int childPosition),返回祖列表的子列表的Id
? ? ? ? ? ? ?* 下面兩個屬性很重要!
? ? ? ? ? ? ?* getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent),該方法決定每個組選項的外觀、
? ? ? ? ? ? ?* getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent),該方法決定每個子選項的外觀、
? ? ? ? ? ? ?*isChildSelectable(int groupPosition,
int childPosition):如果child添加監(jiān)聽事件,則要返回true
Main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/root"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><!--ExpandableListView組件android:childDivider 指定個組內(nèi)各子列表項之間的分隔條android:childIndicator 顯示子列表項旁邊的Drawble對象android:groupIndicator 顯示組列表項旁邊的Drawble對象--><ExpandableListViewandroid:id="@+id/expandableListView1"android:layout_width="match_parent"android:layout_height="wrap_content"android:childDivider="#f0f"></ExpandableListView></LinearLayout> MainActivity.java
package com.hust.expandablelistview;import android.app.Activity; import android.os.Bundle; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.LayoutParams; import android.widget.BaseExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);BaseExpandableListAdapter bela=new BaseExpandableListAdapter(){ /*自動實現(xiàn)這10個方法* getGroupCount(),返回包含組列表的數(shù)量* getChildrenCount(int groupPosition),返回包含組列表的數(shù)量* * getGroup(int groupPosition),返回組列表的對象* getChild(int groupPosition, int childPosition),返回組列表下的子列表對象* * getGroupId(int groupPosition),返回組列表Id* getChildId(int groupPosition, int childPosition),返回祖列表的子列表的Id* * getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent),該方法決定每個組選項的外觀、* getChildView(int groupPosition, int childPosition,boolean isLastChild, View convertView, ViewGroup parent),該方法決定每個子選項的外觀、* * * */int[] logos=new int[]{R.drawable.p,R.drawable.z,R.drawable.t};//組列表的數(shù)量private String[] armTypes=new String[]{"我的好友","高中同學(xué)","大學(xué)同學(xué)"};//組列表下的子列表項,可擴(kuò)展的ExpandableListView是個二維數(shù)組private String[][] arms=new String[][]{{"狂戰(zhàn)士","龍騎士","黑暗圣堂","電兵"},{"張娜","李四","趙龍","錢爽"},{"王燕","劉濤","張?zhí)箍?#34;,"汪明城"}};//返回包含組列表的數(shù)量@Overridepublic int getGroupCount() {// TODO Auto-generated method stubreturn armTypes.length;}//返回組位置下的子列表項的數(shù)量@Overridepublic int getChildrenCount(int groupPosition) {// TODO Auto-generated method stubreturn arms[groupPosition].length;}//返回組列表的對象@Overridepublic Object getGroup(int groupPosition) {// TODO Auto-generated method stubreturn armTypes[groupPosition];}//返回組列表下的子列表對象@Overridepublic Object getChild(int groupPosition, int childPosition) {// TODO Auto-generated method stubreturn arms[groupPosition][childPosition];}//返回組列表Id@Overridepublic long getGroupId(int groupPosition) {// TODO Auto-generated method stubreturn groupPosition;}//返回祖列表的子列表的Id@Overridepublic long getChildId(int groupPosition, int childPosition) {// TODO Auto-generated method stubreturn childPosition;}@Overridepublic boolean hasStableIds() {// TODO Auto-generated method stubreturn true;}//該方法決定每個組選項的外觀、這里這定義組列表布局,也可以用xml文件@Overridepublic View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent) {// TODO Auto-generated method stubLinearLayout ll=new LinearLayout(MainActivity.this);ll.setOrientation(0);ImageView logo=new ImageView(MainActivity.this);logo.setImageResource(logos[groupPosition]);TextView textview=getTextView();textview.setText(getGroup(groupPosition).toString());ll.addView(logo);ll.addView(textview);return ll; }//設(shè)置TextView的參數(shù)private TextView getTextView() {// TODO Auto-generated method stubAbsListView.LayoutParams lp=new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,64);TextView textview=new TextView(MainActivity.this);textview.setLayoutParams(lp);//設(shè)置布局參數(shù),android:layout_Width="match_parent",android:layout_Height="64"textview.setGravity(Gravity.CENTER_VERTICAL|Gravity.LEFT);//android:gravity="CENTER_VERTICAL|LEFT"textview.setPadding(36, 0, 0, 0);textview.setTextSize(16); //android:textsize="20dp" return textview;}//該方法決定每個子選項的外觀@Overridepublic View getChildView(int groupPosition, int childPosition,boolean isLastChild, View convertView, ViewGroup parent) {// TODO Auto-generated method stubTextView text=getTextView();text.setText(getChild(groupPosition,childPosition).toString()); return text;}@Overridepublic boolean isChildSelectable(int groupPosition,int childPosition) {// TODO Auto-generated method stubreturn true;}};ExpandableListView expandablelistview=(ExpandableListView) findViewById(R.id.expandableListView1);//設(shè)置adapterexpandablelistview.setAdapter(bela);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();if (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);} }
二,使用SimpleExpandableListAdapter顯示ExpandableListView
SimpleExpandableListAdapter adapter = new SimpleExpandableListAdapter( this, gruops, R.drawable.expandablelistview_groups, new String[]{"group"}, new int[]{R.id.textGroup}, childs, R.drawable.expandablelistview_child, new String[]{"child"}, new int[]{R.id.textChild} ); * 參數(shù)1.上下文對象Context
* 參數(shù)2.一級條目目錄集合
* 參數(shù)3.一級條目對應(yīng)的布局文件 (expandablelistview_groups.xml文件
* 參數(shù)4.fromto,就是map中的key,指定要顯示的對象
* 參數(shù)5.與參數(shù)4對應(yīng),指定要顯示在groups中的id
* 參數(shù)6.二級條目目錄集合
* 參數(shù)7.二級條目對應(yīng)的布局文件
* 參數(shù)9.與參數(shù)8對應(yīng),指定要顯示在childs中的id
1,定義一個主界面expandablelistview.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><ExpandableListView android:id ="@+id/expandableListView" android:layout_width ="fill_parent" android:layout_height ="wrap_content" ></ExpandableListView> </LinearLayout> 2.在res/drawable目錄下創(chuàng)建樣式文件expandablelistview_groups.xml該界面是組界面:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><TextViewandroid:id="@+id/textGroup" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingLeft="40px" android:paddingTop="6px" android:paddingBottom="6px" android:textSize="15sp" android:text="No data" > </TextView> </LinearLayout> 3.在res/drawable目錄下創(chuàng)建樣式文件expandablelistview_child.xml;是子控件,直接顯示列表內(nèi)容
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><TextView android:id="@+id/textChild" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingLeft="60px" android:paddingTop="10px" android:paddingBottom="10px" android:textSize="20sp" android:text="No Data" /> </LinearLayout>ExpandableListViewDemo_two.java
public class ExpandableListViewDemo_two extends Activity {/** Called when the activity is first created. */ private ExpandableListView expandableListView_one;@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.expandablelistview); expandableListView_one =(ExpandableListView)findViewById(R.id.expandableListView); //創(chuàng)建二個一級條目標(biāo)題 Map<String, String> title_1 = new HashMap<String, String>(); Map<String, String> title_2 = new HashMap<String, String>(); title_1.put("group", "移動開發(fā)"); title_2.put("group", "Web開發(fā)"); //創(chuàng)建一級條目容器 List<Map<String, String>> gruops = new ArrayList<Map<String,String>>(); gruops.add(title_1); gruops.add(title_2); //創(chuàng)建二級條目內(nèi)容 //內(nèi)容一 Map<String, String> content_1 = new HashMap<String, String>(); Map<String, String> content_2 = new HashMap<String, String>(); content_1.put("child", "ANDROID"); content_2.put("child", "IOS"); List<Map<String, String>> childs_1 = new ArrayList<Map<String,String>>(); childs_1.add(content_1); childs_1.add(content_2); //內(nèi)容二 Map<String, String> content_3 = new HashMap<String, String>(); Map<String, String> content_4 = new HashMap<String, String>(); Map<String, String> content_5 = new HashMap<String, String>(); content_3.put("child", "jsp"); content_4.put("child", "servlet"); content_5.put("child", "page"); List<Map<String, String>> childs_2 = new ArrayList<Map<String,String>>(); childs_2.add(content_3); childs_2.add(content_4); childs_2.add(content_5); //存放兩個內(nèi)容, 以便顯示在列表中 List<List<Map<String, String>>> childs = new ArrayList<List<Map<String,String>>>(); childs.add(childs_1); childs.add(childs_2); //創(chuàng)建ExpandableList的Adapter容器 /** * 使用SimpleExpandableListAdapter顯示ExpandableListView * 參數(shù)1.上下文對象Context * 參數(shù)2.一級條目目錄集合 * 參數(shù)3.一級條目對應(yīng)的布局文件 (expandablelistview_groups.xml文件 * 參數(shù)4.fromto,就是map中的key,指定要顯示的對象 * 參數(shù)5.與參數(shù)4對應(yīng),指定要顯示在groups中的id * 參數(shù)6.二級條目目錄集合 * 參數(shù)7.二級條目對應(yīng)的布局文件 * 參數(shù)9.與參數(shù)8對應(yīng),指定要顯示在childs中的id / SimpleExpandableListAdapter adapter = new SimpleExpandableListAdapter( this, gruops, R.drawable.expandablelistview_groups, new String[]{"group"}, new int[]{R.id.textGroup}, childs, R.drawable.expandablelistview_child, new String[]{"child"}, new int[]{R.id.textChild} ); //加入列表 expandableListView_one.setAdapter(adapter); expandableListView_one.setOnChildClickListener(listener);} private OnChildClickListener listener =new OnChildClickListener() {@Overridepublic boolean onChildClick(ExpandableListView parent, View v,int groupPosition, int childPosition, long id) {// TODO Auto-generated method stubtoast("點擊了");return false;}};private void toast(String str) {Toast.makeText(this, str, Toast.LENGTH_LONG).show(); } } 上面的樣式也可以使用系統(tǒng)的自帶的樣式如下:
android.R.layout.simple_expandable_list_item_1,//層顯示樣式 ,系統(tǒng)自定義
android.R.layout.simple_expandable_list_item_2,
ExpandableListActivity直接繼承了Activity。
1,繼承ExpandableListActivity
2,定義好內(nèi)容ExpandableListAdapter,擴(kuò)展BaseExpandableListAdapter和SimpleExpandableListAdapter都可以
3,setListAdapter的方法添加adapter?
package com.example.expandablelistactivity;import android.app.ExpandableListActivity; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseExpandableListAdapter; import android.widget.ExpandableListAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView;public class MainActivity extends ExpandableListActivity//繼承ExpandableListActivity {public void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);//無需布局文件//自定義擴(kuò)展BaseExpandableListAdapterExpandableListAdapter adapter = new BaseExpandableListAdapter(){int[] logos = new int[]{R.drawable.p,R.drawable.z,R.drawable.t};//組列表的數(shù)量private String[] armTypes=new String[]{"我的好友","高中同學(xué)","大學(xué)同學(xué)"};//組列表下的子列表項,可擴(kuò)展的ExpandableListView是個二維數(shù)組private String[][] arms=new String[][]{{"狂戰(zhàn)士","龍騎士","黑暗圣堂","電兵"},{"張娜","李四","趙龍","錢爽"},{"王燕","劉濤","張?zhí)箍?#34;,"汪明城"}};//獲取指定組位置、指定子列表項處的子列表項數(shù)據(jù)@Overridepublic Object getChild(int groupPosition, int childPosition){return arms[groupPosition][childPosition];}@Overridepublic long getChildId(int groupPosition, int childPosition){return childPosition;}@Overridepublic int getChildrenCount(int groupPosition){return arms[groupPosition].length;}private TextView getTextView(){AbsListView.LayoutParams lp = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 64);TextView textView = new TextView(MainActivity.this);textView.setLayoutParams(lp);textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);textView.setPadding(36, 0, 0, 0);textView.setTextSize(16);return textView;}//該方法決定每個子選項的外觀@Overridepublic View getChildView(int groupPosition, int childPosition,boolean isLastChild, View convertView, ViewGroup parent){TextView textView = getTextView();textView.setText(getChild(groupPosition, childPosition).toString());return textView;}//獲取指定組位置處的組數(shù)據(jù)@Overridepublic Object getGroup(int groupPosition){return armTypes[groupPosition];}@Overridepublic int getGroupCount(){return armTypes.length;}@Overridepublic long getGroupId(int groupPosition){return groupPosition;}//該方法決定每個組選項的外觀@Overridepublic View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent){LinearLayout ll = new LinearLayout(MainActivity.this);ll.setOrientation(0);ImageView logo = new ImageView(MainActivity.this);logo.setImageResource(logos[groupPosition]);ll.addView(logo);TextView textView = getTextView();textView.setText(getGroup(groupPosition).toString());ll.addView(textView);return ll;}@Overridepublic boolean isChildSelectable(int groupPosition, int childPosition){return true;}@Overridepublic boolean hasStableIds(){return true;}};// 設(shè)置該窗口顯示列表setListAdapter(adapter);} }
附上源碼更方便學(xué)習(xí):
public class ExpandableListActivity extends Activity implementsOnCreateContextMenuListener,ExpandableListView.OnChildClickListener, ExpandableListView.OnGroupCollapseListener,ExpandableListView.OnGroupExpandListener { ExpandableListAdapter mAdapter;ExpandableListView mList;boolean mFinishedStart = false;/*** Override this to populate the context menu when an item is long pressed. menuInfo* will contain an {@link android.widget.ExpandableListView.ExpandableListContextMenuInfo}* whose packedPosition is a packed position* that should be used with {@link ExpandableListView#getPackedPositionType(long)} and* the other similar methods.* <p>* {@inheritDoc}*/@Overridepublic void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {}/*** Override this for receiving callbacks when a child has been clicked.* <p>* {@inheritDoc}*/public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,int childPosition, long id) {return false;}/*** Override this for receiving callbacks when a group has been collapsed.*/public void onGroupCollapse(int groupPosition) {}/*** Override this for receiving callbacks when a group has been expanded.*/public void onGroupExpand(int groupPosition) {}/*** Ensures the expandable list view has been created before Activity restores all* of the view states.* *@see Activity#onRestoreInstanceState(Bundle)*/@Overrideprotected void onRestoreInstanceState(Bundle state) {ensureList();super.onRestoreInstanceState(state);}/*** Updates the screen state (current list and other views) when the* content changes.* * @see Activity#onContentChanged()*/@Overridepublic void onContentChanged() {super.onContentChanged();View emptyView = findViewById(com.android.internal.R.id.empty);mList = (ExpandableListView)findViewById(com.android.internal.R.id.list);if (mList == null) {throw new RuntimeException("Your content must have a ExpandableListView whose id attribute is " +"'android.R.id.list'");}if (emptyView != null) {mList.setEmptyView(emptyView);}mList.setOnChildClickListener(this);mList.setOnGroupExpandListener(this);mList.setOnGroupCollapseListener(this);if (mFinishedStart) {setListAdapter(mAdapter);}mFinishedStart = true;}/*** Provide the adapter for the expandable list.*/public void setListAdapter(ExpandableListAdapter adapter) {synchronized (this) {ensureList();mAdapter = adapter;mList.setAdapter(adapter);}}/*** Get the activity's expandable list view widget. This can be used to get the selection,* set the selection, and many other useful functions.* * @see ExpandableListView*/public ExpandableListView getExpandableListView() {ensureList();return mList;}/*** Get the ExpandableListAdapter associated with this activity's* ExpandableListView.*/public ExpandableListAdapter getExpandableListAdapter() {return mAdapter;}private void ensureList() {if (mList != null) {return;}setContentView(com.android.internal.R.layout.expandable_list_content);}/*** Gets the ID of the currently selected group or child.* * @return The ID of the currently selected group or child.*/public long getSelectedId() {return mList.getSelectedId();}/*** Gets the position (in packed position representation) of the currently* selected group or child. Use* {@link ExpandableListView#getPackedPositionType},* {@link ExpandableListView#getPackedPositionGroup}, and* {@link ExpandableListView#getPackedPositionChild} to unpack the returned* packed position.* * @return A packed position representation containing the currently* selected group or child's position and type.*/public long getSelectedPosition() {return mList.getSelectedPosition();}/*** Sets the selection to the specified child. If the child is in a collapsed* group, the group will only be expanded and child subsequently selected if* shouldExpandGroup is set to true, otherwise the method will return false.* * @param groupPosition The position of the group that contains the child.* @param childPosition The position of the child within the group.* @param shouldExpandGroup Whether the child's group should be expanded if* it is collapsed.* @return Whether the selection was successfully set on the child.*/public boolean setSelectedChild(int groupPosition, int childPosition, boolean shouldExpandGroup) {return mList.setSelectedChild(groupPosition, childPosition, shouldExpandGroup);}/*** Sets the selection to the specified group.* @param groupPosition The position of the group that should be selected.*/public void setSelectedGroup(int groupPosition) {mList.setSelectedGroup(groupPosition);}}
總結(jié)
以上是生活随笔為你收集整理的UI组件之AdapterView及其子类(六)ExpandableListView组件和ExpandableListActivity的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: UI组件之AdapterView及其子类
- 下一篇: UI组件之 ProgressBar及其子