我遇到ListView
的问题。我有ListView
一些项目(例如,两个有绿色背景颜色,其余有白色。当我点击项目时,其余项目将颜色更改为白色。
例1:
Item1(white)
Item2(green)
Item3(white)
Item4(green)
当我点击Item3时,它看起来像:
Item1(green)
Item2(white)
Item3(green)
Item4(white)
例2:
Item1(white)
Item2(green)
Item3(white)
Item4(white)
当我点击Item3时,它看起来像:
Item1(white)
Item2(white)
Item3(green)
Item4(white)
我该怎么做才能修复它?
编辑: 这是我的代码 onCreate()方法:
protected void onCreate(Bundle savedInstanceState) {
System.out.println("onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paired_devices);
devicesList = (ListView) findViewById(R.id.pairedDevicesListView);
devices = DatabaseHandler.getInstance().getCounters(false);
adapter = new ArrayAdapter(this, R.layout.text_view_layout, devices);
devicesList.setAdapter(adapter);
devicesList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
System.out.println("Click " + devicesList.getItemAtPosition(i));
}
});
}
将项目添加到ListView
:
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("Broadcast Receiver");
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println(device.getName());
for(int i = 0; i < devicesList.getCount(); i++) {
if(device.getName().equals(devices.get(i))) {
View v = devicesList.getChildAt(getItemPosition(device.getName()));
v.setBackgroundColor(Color.GREEN);
}
}
}
}
};
EDIT2 ListView xml
<ListView
android:layout_width="match_parent"
android:layout_height="167dp"
android:id="@+id/pairedDevicesListView"
android:layout_gravity="center_horizontal"
android:layout_weight="0.66"
android:choiceMode="singleChoice" />
text_view_layout
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textviewlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30sp"></TextView>
答案 0 :(得分:0)
您可以这样做:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(dbManager.toggleCheck(list,parent.getItemAtPosition(position).toString()) == 1){
parent.getChildAt(position).setBackgroundColor(Color.parseColor("#2196f3"));
}
else {
parent.getChildAt(position).setBackgroundColor(Color.parseColor("#e3f2fd"));
}
}
});