ExpandableListView是一种可应用于某种环境的下拉列表。
实例代码:
package com.example.lenovo.expandablelistview_demo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private ExpandableListView expandableListView;
private MyBaseExpandableListAdapter adapter;
private String[] group = {"我的好友","陌生人","黑名单"};
private String[][] children = {
{"小王","急急急","kl","考虑"},
{"流域","蜡笔","一扭"},
{"ren","du","处矛"}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.expandableListView = (ExpandableListView) this.findViewById(R.id.expandableListView);
adapter = new MyBaseExpandableListAdapter();
this.expandableListView.setAdapter(adapter);
}
private final class MyBaseExpandableListAdapter extends BaseExpandableListAdapter{
@Override
//返回组中元素的个数
public int getGroupCount() {
return group.length;
}
@Override
//根据组的索引返回当前组中子元素的个数
public int getChildrenCount(int groupPosition) {
return children[groupPosition].length;
}
@Override
//返回指定组索引处的元素值
public Object getGroup(int groupPosition) {
return group[groupPosition];
}
@Override
//返回指定组索引和子元素索引对应的值
public Object getChild(int groupPosition, int childPosition) {
return children[groupPosition][childPosition];
}
@Override
//返回组的id值
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
//返回指定组中的子元素指定索引的值
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
//当绘制组的View对象时自动调用的方法
/**
* groupPosition :组的索引值
* isExpanded:当前组下的元素是否被展开
*
*/
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View view = View.inflate(MainActivity.this,R.layout.group_view,null);
TextView textView_group = (TextView) view.findViewById(R.id.textView_group);
//得到组名
String groupName = group[groupPosition];
textView_group.setText(groupName);
return view;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
View view = View.inflate(MainActivity.this,R.layout.child_view,null);
TextView textView_child = (TextView) view.findViewById(R.id.textView_child);
String childrenName = children[groupPosition][childPosition];
textView_child.setText(childrenName);
return view;
}
@Override
//子元素是否被选中,默认值为false,表示不能被选中
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
}