你的位置:首页 > 操作系统

[操作系统]安卓开发树形控件之ExpandableListView(一)


  这个例子非常简单,简单到一个初学者都能随便开发出来,今天的目的仅仅只是为了将效果实现出来,如果想深入这里有几篇非常不错的博客:

 

Android 之ExpandableListView几个特殊的属性

http://blog.csdn.net/t12x3456/article/details/7828620

ExpandableListView讲解
http://www.apkbus.com/thread-124715-1-1.html

和使用listview一样,我们这里需要继承一个适配器,叫做BaseExpandListAdapter;然后重写几个父类的方法

package com.example.uitest;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;

public class TreeAdapter extends BaseExpandableListAdapter{

Context context;


public TreeAdapter(Context context) {
super();
this.context = context;
}

@Override
public Object getChild(int arg0, int arg1) {
return 0;
}

@Override
public long getChildId(int arg0, int arg1) {
// TODO Auto-generated method stub
return 0;
}

@Override
public View getChildView(int arg0, int arg1, boolean arg2, View v,
ViewGroup arg4) {
v = LayoutInflater.from(context).inflate(R.layout.item2, null);
return v;
}

@Override
public int getChildrenCount(int arg0) {
// TODO Auto-generated method stub
return 3;
}

@Override
public Object getGroup(int arg0) {
// TODO Auto-generated method stub
return null;
}

@Override
public int getGroupCount() {
return 3;
}

@Override
public long getGroupId(int arg0) {
return 0;
}

@Override
public View getGroupView(int arg0, boolean arg1, View v, ViewGroup vgs) {
v = LayoutInflater.from(context).inflate(R.layout.item_autocomplete, null);
return v;
}

@Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}

@Override
public boolean isChildSelectable(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}

}

这里我们只操作了四个函数,分别是:

public int getChildrenCount(int arg0) ;//获取二级列表的子布局总记录,也就是行数

public int getGroupCount();//获取一级列表的行数

public View getChildView(int arg0, int arg1, boolean arg2, View v,
ViewGroup arg4);//获取二级列表的资源布局

public View getGroupView(int arg0, boolean arg1, View v, ViewGroup vgs);//获取一级列表的行数

最后将适配器加载至ExpandableListView中:

ExpandableListView view = (ExpandableListView)findViewById(R.id.elv);
TreeAdapter adapter = new TreeAdapter(getApplicationContext());
view.setAdapter(adapter);

主布局

<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent" >

<ExpandableListView
android:id="@+id/elv"
android:layout_width="fill_parent"

 android:groupIndicator="@null"
android:layout_height="wrap_content"></ExpandableListView>


</LinearLayout>

这是最浓缩版了大家应该很快可以懂;