ExpandableListView
是一个可以展开和收起子列表项的 Android 控件,非常适合用于实现侧边栏导航
- 在
activity_main.xml
布局文件中添加ExpandableListView
:
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" tools:openDrawer="start">
- 创建一个数据模型类,例如
NavigationItem
,用于存储导航项的信息:
public class NavigationItem { private String title; private int icon; public NavigationItem(String title, int icon) { this.title = title; this.icon = icon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getIcon() { return icon; } public void setIcon(int icon) { this.icon = icon; } }
- 创建一个自定义适配器,继承自
BaseExpandableListAdapter
,用于填充ExpandableListView
:
public class NavigationAdapter extends BaseExpandableListAdapter { private Context context; private ListgroupList; private Map > childListMap; public NavigationAdapter(Context context, List groupList, Map > childListMap) { this.context = context; this.groupList = groupList; this.childListMap = childListMap; } // ... 实现 BaseExpandableListAdapter 中的方法 }
- 在
MainActivity
中初始化数据并设置适配器:
public class MainActivity extends AppCompatActivity { private DrawerLayout drawerLayout; private ExpandableListView navigationList; private NavigationAdapter navigationAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); drawerLayout = findViewById(R.id.drawer_layout); navigationList = findViewById(R.id.navigation_list); // 初始化数据 ListgroupList = new ArrayList<>(); Map > childListMap = new HashMap<>(); NavigationItem group1 = new NavigationItem("Group 1", R.drawable.ic_group_1); NavigationItem group2 = new NavigationItem("Group 2", R.drawable.ic_group_2); groupList.add(group1); groupList.add(group2); List childList1 = new ArrayList<>(); childList1.add(new NavigationItem("Child 1", R.drawable.ic_child_1)); childList1.add(new NavigationItem("Child 2", R.drawable.ic_child_2)); List childList2 = new ArrayList<>(); childList2.add(new NavigationItem("Child 3", R.drawable.ic_child_3)); childList2.add(new NavigationItem("Child 4", R.drawable.ic_child_4)); childListMap.put(group1, childList1); childListMap.put(group2, childList2); // 设置适配器 navigationAdapter = new NavigationAdapter(this, groupList, childListMap); navigationList.setAdapter(navigationAdapter); // 设置点击事件 navigationList.setOnChildClickListener((parent, v, groupPosition, childPosition, id) -> { // 处理子项点击事件 return false; }); navigationList.setOnGroupClickListener((parent, v, groupPosition, id) -> { // 处理分组点击事件 return false; }); } }
现在你已经成功地使用 ExpandableListView
实现了一个侧边栏导航。你可以根据需要自定义导航项的样式和行为。