我正在尝试突出显示 Android 测验程序中的选定行。但是,我得到了一些奇怪的行为。基本上,传递给 onListItemClick 的位置正确地反映了支持数据数组中的位置,但是显然使用子索引查找的视图是错误的。子索引似乎与位置相反,就像一个堆栈。使用这个假设,我可以使代码工作,但它是违反直觉的。
这是代码:
public class QuestionActivity extends ListActivity {
...
/*
* Create the adapter
*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.simple_list_item_single_choice_custom,
mAppState.mAnswerArray) {
};
/* attach the adapter to the ListView */
setListAdapter(adapter);
/* set ListView's choice mode to single */
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
……
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// always four rows; assume last row is zeroth child. Therefore,
// if the first row is chosen (0 position) you need to get child 3.
// 3 - 0 = 3.
int childCount = l.getChildCount();
int lastViewPos = childCount - 1;
View selView = l.getChildAt(lastViewPos - position);
}
...
<TextView android:id="@+id/display_question"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textSize="40sp" android:typeface="normal" android:padding="10dp"
android:layout_gravity="center_vertical|center_horizontal"
android:textColor="@color/text_color" />
/>
<ListView android:id="@+id/android:list"
android:cacheColorHint="#00000000" android:layout_height="wrap_content"
android:layout_width="fill_parent" android:textColor="@color/text_color"
android:divider="#00000000" android:dividerHeight="0sp"
android:focusable="false">
</ListView>
<TextView android:id="@+id/display_english"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:paddingLeft="20dp" android:layout_gravity="center_vertical|center_horizontal"
android:textSize="30sp" android:textColor="@color/text_color" />
<Button android:id="@+id/next_button1" android:text="@string/next_question"
android:textSize="15dp" android:layout_gravity="center_vertical|center_horizontal"
android:textColor="@color/text_color" android:background="@drawable/custom_button"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout>
... 这是 simple_list_item_single_choice_custom.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30sp"
android:gravity="center_vertical"
android:checkMark="?android:attr/listChoiceIndicatorSingle"
android:paddingLeft="20dip"
android:textColor="@color/text_color"
android:background="@drawable/custom_list"
/>
我还尝试不在 onClick 事件上调用 super ,并从代码中在列表视图上设置 stackFromBottom ,无论是真还是假,但这些似乎都没有任何区别。
有什么更令人满意、更直观的方法来做到这一点?