【发布时间】:2018-03-19 08:53:32
【问题描述】:
我有 Listview、ArrayAdapter 和 ArrayAdapter 的布局作为 ItemView。
现在,我已经设法更改了选定/单击项目布局的背景颜色。
But how can I change the background color to the original when another item is selected?
代码示例:
Listview listview;
int PREVIOUSLY_SELECTED_ID = -1;
if (arrayList != null) {
Collections.sort(arrayList);
arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, arrayList){
@NonNull
@Override public View getView(final int position, final View convertView, @NonNull final ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
// This is the Layout File "listitem_layout.xml" i am inflating to arrayadapter.
@SuppressLint({"ViewHolder", "InflateParams"}) final View view = layoutInflater.inflate(R.layout.listitem_layout, null, true);
// This is the RelativeLayout in "listitem_layout.xml".
final RelativeLayout relativeLayout = (RelativeLayout) view.findViewById(R.id.relativelayout_selected_item);
// This is onClick event of "relativelayout".
relativeLayout.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
if (PREVIOUSLY_SELECTED_ID != position)
{
// Here, i am changing background color of relativelayout when item is clicked.
v.setBackgroundResource(R.color.tomatoLight);
if(PREVIOUSLY_SELECTED_ID != -1)
{
// Here, i want to change Previously Selected Item's Background Color to it's original(Which is 'Orange').
listView.getAdapter().getView(position,convertView,parent).setBackgroundResource(R.color.orange);
}
PREVIOUSLY_SELECTED_ID = position;
}
else
{
v.setBackgroundResource(R.color.orange);
}
});
return view;
}
};
listView.setAdapter(arrayAdapter);
}
【问题讨论】:
-
您是否添加了任何标志来检测所选项目?
-
是的 "SELECTED_ID" 是 int 标志,用于记住最后选择的 id。
-
你的arrayList上有多少数据?
-
您需要设置一个标志来检测数据列表中的选定项目。
-
单个“SELECTED_ID”是不够的,应该有这些 id 的数组,在你的数组适配器中 if(SELECTED_ID[current]==selected)then color_selected else color_not_selected
标签: android listview android-arrayadapter