ExpandableListView使用

我叫阿狸貓發表於2014-04-17

佈局檔案

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ExpandableListView 
        android:id="@+id/ev"
        android:layout_width="match_parent"
    	android:layout_height="match_parent"></ExpandableListView>
</LinearLayout>

Activity

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;

public class MainActivity extends Activity {

	private ExpandableListView ev;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		ev = (ExpandableListView) findViewById(R.id.ev);
		ev.setAdapter(new MyAdapter());
	}
	//Position從0開始
	private class MyAdapter extends BaseExpandableListAdapter{
		//返回分組的個數
		public int getGroupCount() {
			return 5;
		}
		//返回每個分組裡要顯示的個數
		public int getChildrenCount(int groupPosition) {
			return 3;
		}
		//返回某個分組物件(用不到)
		public Object getGroup(int groupPosition) {
			return null;
		}
		//返回某個分組下的子節點(用不到)
		public Object getChild(int groupPosition, int childPosition) {
			return null;
		}
		//獲取分組id,一般用分組的索引
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}
		//獲取子條目id		groupPosition 分組的索引    childPosition子條目的id
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}
		//如果你用position當id ,那就是不穩定的,如果有自己特定的id那就是穩定的 就是幹這個用的  true穩定 false不穩定
		public boolean hasStableIds() {
			return false;
		}
		//返回某個位置分組顯示的內容
		public View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent) {
			TextView tv = new TextView(getApplicationContext());
			tv.setTextSize(30);
			tv.setText("     標題"+groupPosition);
			return tv;
		}
		//返回某個分組的某個子節點的View物件
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			TextView tv = new TextView(getApplicationContext());
			tv.setTextSize(15);
			tv.setText("     內容"+childPosition);
			return tv;
		}
		//返回子節點是否可以被點選  預設是false
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}
	}
}


相關文章