我有一个ListView
:
<ListView
android:id="@+id/sensorList"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_centerHorizontal="true"
android:layout_margin="16dp"
android:layout_below="@+id/chooseHint"
android:choiceMode="multipleChoice" >
</ListView>
其中有 CheckedTextView
:
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_margin="5dp"
style="@android:style/TextAppearance.Medium"
android:checkMark="?android:attr/listChoiceIndicatorMultiple" />
我添加了一个 OnItemClickListener
来在单击列表项时执行某些操作。而且当单击某个项目时,复选框也会被切换。我怎样才能实现监听器捕获点击事件,但复选框没有捕获?
最佳答案
要防止 CheckedTextView
切换,请执行以下操作:
1. 子类CheckedTextView
。
2. 重写setChecked(boolean)
方法。
3. 将 CheckedTextView
替换为被覆盖的 View 。
步骤 1 和 2 的代码:
package com.example.multichoicelist;
public class UnresponsiveCheckedTextView extends CheckedTextView {
public UnresponsiveCheckedTextView(Context context) {
this(context, null);
}
public UnresponsiveCheckedTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public UnresponsiveCheckedTextView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setChecked(boolean checked) {
//Do nothing.
}
}
正是setChecked
方法刷新了CheckedTextView
的选中状态,从而带来了切换效果。覆盖 setChecked
将阻止用户单击列表项时切换 CheckedTextView
的复选框。
第 3 步的 XML:
<com.example.multichoicelist.UnresponsiveCheckedTextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView"
style="@android:style/TextAppearance.Medium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
/>
下面的 Activity 包含一个多选 ListView
以及一个显示已单击的列表项的 OnItemClickListener
。请注意,在此类点击事件期间,复选框不会切换(由于覆盖了 CheckedTextView
实现):
package com.example.multichoicelist;
public class MainActivity extends ListActivity implements OnItemClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView mListView = getListView();
mListView.setOnItemClickListener(this);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mListView.setAdapter(ArrayAdapter.createFromResource(this,
R.array.phonetic_alphabet, R.layout.list_item));
}
@Override
public void onItemClick(AdapterView<?> arg0, View childView,
int adapterPosition, long arg3) {
Toast.makeText(this,
((CheckedTextView) childView).getText() + " selected",
Toast.LENGTH_SHORT).show();
}
}
下图显示了单击名为“Charlie”的列表项时多选 ListView
的行为:
关于android - ListView 监听器不拦截来自项目的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17739293/