我正在开发一个带有 ListActivity 的 Android 2.3.3 应用程序。
我想做一些事情来向用户展示他/她选择的项目。我已经完成了以下操作,但它没有(我在 stackoverflow 中搜索,它们是相互矛盾的答案)。
这是 layout_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/txtName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/selector"
android:text="" />
</LinearLayout>
这是 res/drawable 上的 selector.xml 文件
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true"
android:color="#00FF00" />
<item android:state_pressed="true"
android:color="#555555" />
<item android:color="#000000" />
</selector>
但它不起作用,因为它说我必须@drawable
放入selector.xml
.
如何将背景颜色设置为蓝色以最后单击列表项?
更新
与此列表一起使用的阵列适配器:
public class GatesAdapter extends ArrayAdapter<Gate>
{
/**
* Application context.
*/
private Context context;
/**
*
*/
private int itemLayoutId;
/**
*
*/
private ArrayList<Gate> gates;
private int selectedGateIndex;
public int getSelectedGateIndex() {
return selectedGateIndex;
}
public void setSelectedGateIndex(int selectedGateIndex) {
this.selectedGateIndex = selectedGateIndex;
}
public Gate getSelectedGate()
{
return gates.get(selectedGateIndex);
}
public void removeSelectedGate()
{
this.gates.remove(selectedGateIndex);
}
public ArrayList<Gate> getGates()
{
return this.gates;
}
public GatesAdapter(Context context, int listItemResourceId,
ArrayList<Gate> objects)
{
super(context, listItemResourceId, objects);
this.context = context;
this.itemLayoutId = listItemResourceId;
this.gates = objects;
this.selectedGateIndex = -1;
this.setNotifyOnChange(true);
}
@Override
public int getCount()
{
return gates.size();
}
@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
Log.v("GatesAdapter", "getView.postion: " + position);
View row = convertView;
if (row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(itemLayoutId, parent, false);
}
Gate gate = gates.get(position);
if (gate != null)
{
TextView itemText = (TextView)row.findViewById(android.R.id.text1);
if (itemText != null)
{
itemText.setText(gate.getName());
//selectedGateIndex = position;
if (selectedGateIndex == position)
{
row.setBackgroundColor(Color.BLUE);
}
}
}
return row;
}
}