android 带标题的列表
时间: 2023-08-20 16:03:59 浏览: 55
要在 Android 中创建带标题的列表,可以使用 ExpandableListView 组件。 ExpandableListView 可以显示可展开的列表,其中每个列表项都可以展开以显示附加的子项。以下是创建带标题的 ExpandableListView 的基本步骤:
1. 创建一个带有 ExpandableListView 的布局文件。
2. 创建适配器来为 ExpandableListView 提供数据。
3. 在适配器中实现必要的方法,例如 getGroupCount()、getChildCount()、getGroupView() 和 getChildView()。
4. 将适配器设置为 ExpandableListView。
5. 在 Activity 中处理 ExpandableListView 中的项目单击事件。
以下是一个简单的示例代码:
```java
public class MainActivity extends AppCompatActivity {
private ExpandableListView listView;
private MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ExpandableListView) findViewById(R.id.expandableListView);
adapter = new MyAdapter(this);
listView.setAdapter(adapter);
}
private class MyAdapter extends BaseExpandableListAdapter {
private Context context;
public MyAdapter(Context context) {
this.context = context;
}
@Override
public int getGroupCount() {
return 3;
}
@Override
public int getChildrenCount(int groupPosition) {
return 5;
}
@Override
public Object getGroup(int groupPosition) {
return "Group " + groupPosition;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return "Child " + childPosition;
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
TextView textView = new TextView(context);
textView.setText("Group " + groupPosition);
textView.setTextSize(20);
textView.setPadding(100, 25, 0, 25);
textView.setBackgroundColor(Color.LTGRAY);
return textView;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
TextView textView = new TextView(context);
textView.setText("Child " + childPosition);
textView.setTextSize(16);
textView.setPadding(150, 10, 0, 10);
return textView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
}
```
在这个示例中,我们创建了一个带有三个组和每个组中五个子项的 ExpandableListView。每个组都有一个标题,并使用 TextView 来显示。每个子项都是一个 TextView,没有标题。你可以根据需要修改适配器中的方法和视图来创建自己的带标题的列表。