系統: Android 4.0.3
使用過的人AdapterView一定知道有三個必備的元素
第一個 : AdapterView本身
第二個 : Data
第三個 : Adapter
現在來一個一個解決他們
第一個 : AdapterView (使用ExpandableListView)
xml :
<ExpandableListView
android:id="@+id/expandableListView1"
android:groupIndicator="@null"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ExpandableListView>
之後就 findViewById...不用說了
第二個 : Data
Data分成兩個部分 : Group還有Child
範例如下:
Group部分: 一共三個人
List<String>
_GroupList = new
ArrayList<String>();
_GroupList.add("Maca");
_GroupList.add("Paca");
_GroupList.add("Waca");
Child部分:
List<View> _ChildList
= new
ArrayList<View>();
TextView _TextView1 = new TextView(this);
_TextView1.setText("Hello Maca");
_TextView1.setTextColor(Color.RED);
TextView _TextView2 = new TextView(this);
_TextView2.setText("Hello Paca");
_TextView2.setTextColor(Color.RED);
TextView _TextView3 = new TextView(this);
_TextView3.setText("Hello Waca");
_TextView3.setTextColor(Color.RED);
_ChildList.add(_TextView1);
_ChildList.add(_TextView2);
_ChildList.add(_TextView3);
第三個 : Adapter
這個地方看起來最複雜 但是實際上就是看名稱實現他們而已
主要是看自己的需求再來看怎樣實現他們
以下是範例
class MyAdapter extends BaseExpandableListAdapter
{
private Context mContext;
private List<String> mGroupList;
private List<View> mChildList;
public MyAdapter(Context
pContext,List<String> pGroupList,List<View> pChildList)
{
mContext = pContext;
mGroupList = pGroupList;
mChildList = pChildList;
}
public Object getChild(int groupPosition, int childPosition)
{
return mChildList.get(childPosition);
}
public long getChildId(int groupPosition, int childPosition)
{
// TODO Auto-generated method stub
return 0;
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View
convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
return mChildList.get(groupPosition);
}
public int getChildrenCount(int groupPosition)
{
// TODO Auto-generated method stub
return 1;
}
public Object getGroup(int groupPosition)
{
// TODO Auto-generated method stub
return mGroupList.get(groupPosition);
}
public int getGroupCount()
{
// TODO Auto-generated method stub
return mGroupList.size();
}
public long getGroupId(int groupPosition)
{
// TODO Auto-generated method stub
return 0;
}
public View getGroupView(int groupPosition, boolean isExpanded, View
convertView,
ViewGroup parent)
{
TextView _View = new TextView(mContext);
_View.setText(mGroupList.get(groupPosition));
return _View;
}
public boolean hasStableIds()
{
// TODO Auto-generated method stub
return false;
}
public boolean isChildSelectable(int groupPosition, int childPosition)
{
// TODO Auto-generated method stub
return false;
}
}
最後記得要把它們串在一起:
MyAdapter _Adapter = new MyAdapter(this, _GroupList,
_ChildList);
_ExpandableListView.setAdapter(_Adapter);
完成!!
效果圖:
發現有個礙眼的圖標所以在 xml 加上這行把圖標的位置指向null
android:groupIndicator="@null"
搞定
沒有留言:
張貼留言