我有一个实现 ListView 的相当简单的程序。当我在列表中选择一个项目时,它会短暂变为橙色,然后恢复为黑色。但是,我希望在我选择该项目后它保持橙色(直到我清除该项目或选择其他项目)。我试图对此进行编码,但失败了。我认为它必须接近正确。谁能告诉我需要在下面的代码中修改什么才能使其工作?
文件:./res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:gravity="center">
<ListView
android:id="@android:id/list" android:layout_width="match_parent"
android:layout_height="match_parent" android:background="@drawable/list_selector"/>
</LinearLayout>
文件:./res/drawable/list_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:drawable="@color/orange" />
<item android:state_selected="false" android:drawable="@android:color/black" />
</selector>
文件:./res/values/colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources> <color name="orange">#b0e0e6</color> </resources>
文件:./src/com/commonsware/android/linearpct/LinearLayoutDemo.java
public class LinearLayoutDemo extends ListActivity implements OnItemClickListener {
private static final String[] items={"1", "2", "4", "8", "16", "32", "64", "128", "256", "512", "1024", "2048", "4096", "8192"};
ListView myLV;
ArrayAdapter myAdapter;
@Override public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Log.d("LinearLayoutDemo:", "********: onCreate() begin");
getListView().setOnItemClickListener(this);
myAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
myLV = (ListView) findViewById(android.R.id.list);
myLV.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
myLV.setAdapter(myAdapter);
}
@Override public void onItemClick(AdapterView<?> arg0, View view, int position, long lng) {
view.setSelected(true);
String selectedFromList =(String) (myLV.getItemAtPosition(position));
Log.d("LinearLayoutDemo:", "********: OnItemClick: " + selectedFromList);
}
@Override public void onListItemClick(ListView parent, View view, int position, long id) {
super.onListItemClick(parent, view, position, id);
view.setSelected(true);
String selectedFromList =(String) (myLV.getItemAtPosition(position));
Log.d("LinearLayoutDemo:", "********: OnItemClick: " + selectedFromList);
}
}
注意:当我运行此代码时,来自 onListItemClick() 的日志消息永远不会显示在日志中。所以那里出了点问题。
另外,我不知道如何在 onItemClick() 中调用 super.onItemClick()。这可能是一个线索。