我有一个带有 ListView 的应用程序。 ListView 工作正常。当我希望列表以标记的某些行开始时,问题就开始了。如果我按下它,我可以标记一行。但是,似乎找不到在初始化时标记任何行的方法。
这是我的代码:
listViewOfBluetooth = getListView();
setInitialEnabledDevices();
listViewOfBluetooth.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String chosenBluetoothDevice = (String) ((TextView) view).getText();
BluetoothEnableOrDisable(view, chosenBluetoothDevice);
Toast.makeText(getApplicationContext(), chosenBluetoothDevice, Toast.LENGTH_SHORT).show();
editor.putString("bluetooth_name_from_list1", chosenBluetoothDevice);
editor.putBoolean("have_the_cars_bluetooth", true);
editor.commit();
Intent intent = new Intent(List.this, ParkOGuardActivity.class);
startActivity(intent);
}
});
}
public static void setInitialEnabledDevices(){
int length = listViewOfBluetooth.getChildCount();
View view = null;
String first = prefs.getString("bluetooth_name_from_list0", "");
String second = prefs.getString("bluetooth_name_from_list1", "");
String third = prefs.getString("bluetooth_name_from_list2", "");
for(int i = 0; i < length; i++){
view = listViewOfBluetooth.getChildAt(i);
if(view.equals(first) || view.equals(second) || view.equals(third)) {
view.setBackgroundColor(Color.GRAY);
}
}
}
我该如何解决?
谢谢!
最佳答案
您可以使用自定义适配器实现此目的。这是解决方法。
- 初始化您的自定义适配器
- 为标记的设备名称添加一些标志。
- 覆盖
getView()
并检查标志。并相应地设置列表项的背景。
如果您不明白或遇到任何复杂问题,请回复。
更新:
这是一个示例适配器。我没有编译代码。所以可能会有一些错误。
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class TestAdapter extends BaseAdapter
{
ArrayList<String> deviceNames;
ArrayList<Boolean> selected;
Context context;
public TestAdapter(Context context)
{
this.context = context;
deviceNames = new ArrayList<String>();
selected = new ArrayList<Boolean>();
}
public void addDeviceToList(String deviceName, boolean isSelected)
{
deviceNames.add(deviceName);
selected.add(isSelected);
notifyDataSetChanged();
}
public int getCount()
{
return deviceNames.size();
}
public Object getItem(int position)
{
return deviceNames.get(position);
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
TextView tv = new TextView(context);
tv.setText(deviceNames.get(position));
if(selected.get(position) == true)
{
tv.setBackgroundColor(Color.parseColor("#ff0000"));
}
return tv;
}
}
现在创建适配器对象并将适配器设置为 listView。并通过调用 addDeviceToList()
方法添加单个项目。
关于android - 如何在 ListView 中标记 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10828657/