求Android Java一行代码实现带单选高亮的ListView解决方案
一行代码实现带单选高亮的ListView方案
核心实现思路
通过自定义ListView子类封装所有逻辑,对外暴露SetData方法,让调用方只需一行代码完成数据绑定和单选高亮功能。
1. 自定义ListView子类
创建SingleSelectHighlightListView,封装单选模式、主题适配的高亮逻辑:
public class SingleSelectHighlightListView extends ListView { private ArrayAdapter<?> adapter; private int selectedPosition = -1; public SingleSelectHighlightListView(Context context) { super(context); init(); } public SingleSelectHighlightListView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public SingleSelectHighlightListView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { // 启用单选模式 setChoiceMode(CHOICE_MODE_SINGLE); } public void SetData(Object[] data) { // 初始化适配器,支持字符串或重写toString()的对象数组 adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, data) { @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View view = super.getView(position, convertView, parent); TextView textView = view.findViewById(android.R.id.text1); // 基于主题属性动态设置选中/未选中样式 int colorPrimary = ContextCompat.getColor(getContext(), R.attr.colorPrimary); int colorOnPrimary = ContextCompat.getColor(getContext(), R.attr.colorOnPrimary); int colorSurface = ContextCompat.getColor(getContext(), R.attr.colorSurface); int colorOnSurface = ContextCompat.getColor(getContext(), R.attr.colorOnSurface); if (position == selectedPosition) { textView.setBackgroundColor(colorPrimary); textView.setTextColor(colorOnPrimary); } else { textView.setBackgroundColor(colorSurface); textView.setTextColor(colorOnSurface); } return view; } }; setAdapter(adapter); // 处理项点击事件,更新选中状态 setOnItemClickListener((parent, view, position, id) -> { selectedPosition = position; adapter.notifyDataSetChanged(); }); } }
2. 布局中使用自定义ListView
在XML布局文件里添加该自定义控件:
<com.yourpackage.SingleSelectHighlightListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent" />
3. 调用示例(一行代码绑定数据)
完全符合你给出的示例调用方式:
String tutorials[] = { "Algorithms", "Data Structures", "Languages", "Interview Corner", "GATE", "ISRO CS", "UGC NET CS", "CS Subjects", "Web Technologies" }; SingleSelectHighlightListView l = findViewById(R.id.list); l.SetData(tutorials);
满足条件验证
- API 16+ 兼容:所有用到的API(
ContextCompat.getColor、ListView.CHOICE_MODE_SINGLE、ArrayAdapter)均在API 16及以上版本支持,无兼容性问题。 - 自动适配主题:通过
?attr/colorPrimary、?attr/colorOnPrimary等系统主题属性获取颜色,会自动跟随Activity的深浅主题切换样式(深色主题下选中项为浅色背景+深色文字,浅色主题下相反)。 - 支持多种数据源:
ArrayAdapter默认调用对象的toString()方法,因此无论是字符串数组,还是重写了toString()的自定义对象数组,都能直接作为参数传入SetData方法。
内容的提问来源于stack exchange,提问作者Pony Speed
相关产品推荐
相关产品推荐

