注意:下面的响应是针对不可展开的列表。
这绝对是可行的。您不仅可以为选项和标题创建行,还可以为分隔符创建行,并为这些分隔符行提供您想要的样式(高度 0.5dp,所需的边距)。
基本上,与https://stackoverflow.com/a/13634801/1816603 中建议的解决方案相同,但使用 4 种布局:2 个用于选项(用于父级和子级),2 个用于分隔符(父级分隔符和子级分隔符)。
为简单起见,项目类型和内容可以放在同一个字符串中,或者为了更优雅的解决方案,您可以创建一个包含行类型和行文本的类。
final ListView drawerList = (ListView) findViewById(R.id.left_drawer);
// Add options to the list drawer
final List<String> listOptions = new ArrayList<>();
listOptions.add("1Parent 1");
listOptions.add("2Child 1");
listOptions.add("4");
listOptions.add("2Child 2");
listOptions.add("3");
listOptions.add("1Parent 2");
listOptions.add("3");
listOptions.add("1Parent 3");
drawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item_parent, listOptions) {
@Override
public boolean areAllItemsEnabled()
{
return false;
}
@Override
public boolean isEnabled(int position)
{
String selected = listOptions.get(position);
if ( (selected.charAt(0) == '3') || (selected.charAt(0) == '4') )
return false;
else return true;
}
@Override
public View getView(int position, View coverView, ViewGroup vg) {
LayoutInflater inflater = (LayoutInflater) parent.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int type = getItemViewType(position);
if (type == 1) // parent
{
View rowView = inflater.inflate(R.layout.list_item_parent, vg, false);
TextView text1 = (TextView) rowView.findViewById(R.id.list_item_text);
text1.setText(listOptions.get(position).substring(1));
return rowView;
}
else if (type == 2) // child
{
View rowView = inflater.inflate(R.layout.list_item_child, vg, false);
TextView text1 = (TextView) rowView.findViewById(R.id.list_item_text);
text1.setText(listOptions.get(position).substring(1));
return rowView;
}
else if (type == 3) // parent separator
{
View rowView = inflater.inflate(R.layout.list_separator_parent, vg, false);
return rowView;
}
else if (type == 4) // child separator
{
View rowView = inflater.inflate(R.layout.list_separator_child, vg, false);
return rowView;
}
}
@Override
public int getViewTypeCount() {
return 4;
}
@Override
public int getItemViewType(int position) {
String selected = listOptions.get(position);
return Character.getNumericValue(selected.charAt(0)) - 1;
}
});
布局将被定义为:
list_item_parent - Row with full width, for the text of the parent options
list_item_child - Row with margin on the left, for the text of the parent options
list_separator_parent - Row with dark background, height 0.5dp and full width
list_separator_child - Row with dark background, height 0.5dp and margin on the left