安卓适配器条目选中设置边框
时间: 2023-07-07 13:29:52 浏览: 50
您可以通过在适配器的getView()方法中,根据是否选中来设置条目的背景或边框,以达到选中条目高亮的效果。示例代码如下:
```java
public View getView(int position, View convertView, ViewGroup parent) {
// 获取当前条目的数据
String item = getItem(position);
// 加载布局
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_layout, parent, false);
// 获取条目的控件
TextView textView = convertView.findViewById(R.id.text_view);
// 设置控件的文本
textView.setText(item);
// 判断当前条目是否被选中
if (isItemChecked(position)) {
// 设置选中条目的背景或边框
convertView.setBackground(ContextCompat.getDrawable(getContext(), R.drawable.selected_item_bg));
}
else {
// 设置未选中条目的背景或边框
convertView.setBackground(ContextCompat.getDrawable(getContext(), R.drawable.default_item_bg));
}
return convertView;
}
```
在上述代码中,我们通过isItemChecked()方法来判断当前条目是否被选中。如果选中,则设置选中条目的背景或边框为selected_item_bg,否则设置为default_item_bg。您需要在drawable文件夹下创建这两个对应的背景或边框资源文件。