我现在正在寻找 ListView 中可点击项目的解决方案几天。
首先我遇到了这个: developer.android.com/resources/articles/touch-mode.html 并发现它没有“正常”的 onListItemClick() 行为。
然后我遇到了这段代码: http://www.androidsnippets.org/snippets/125/
// LINE 296-321
@Override
protected ViewHolder createHolder(View v) {
// createHolder will be called only as long, as the ListView is not filled
// entirely. That is, where we gain our performance:
// We use the relatively costly findViewById() methods and
// bind the view's reference to the holder objects.
TextView text = (TextView) v.findViewById(R.id.listitem_text);
ImageView icon = (ImageView) v.findViewById(R.id.listitem_icon);
ViewHolder mvh = new MyViewHolder(text, icon);
// Additionally, we make some icons clickable
// Mind, that item becomes clickable, when adding a click listener (see API)
// so, it is not necessary to use the android:clickable attribute in XML
icon.setOnClickListener(new ClickableListAdapter.OnClickListener(mvh) {
public void onClick(View v, ViewHolder viewHolder) {
// we toggle the enabled state and also switch the icon
MyViewHolder mvh = (MyViewHolder) viewHolder;
MyData mo = (MyData) mvh.data;
mo.enable = !mo.enable; // toggle
ImageView icon = (ImageView) v;
icon.setImageBitmap(
mo.enable ? ClickableListItemActivity.this.mIconEnabled
: ClickableListItemActivity.this.mIconDisabled);
}
});
在调试时,我注意到参数View v是一个TextView,而不是一个“普通” View ,然后当然:
TextView text = (TextView) v.findViewById(R.id.listitem_text);
返回null并且我得到一个NullPointerException...
有什么想法吗?我该如何解决这个问题?
提前致谢! :)
最佳答案
如何创建 ClickableListAdapter
实例?
当您创建列表适配器时,您必须传递一个资源 ID viewId
,这应该是一个 layout
,稍后将被扩充。
public ClickableListAdapter(Context context, int viewid, List objects) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
mDataObjects = objects;
mViewId = viewid;
下面的代码会膨胀传递给构造函数的 xml 布局并调用 createHolder
。
view = mInflater.inflate(mViewId, null);
// call the user's implementation
holder = createHolder(view);
因此,请确保在实例化 ClickableListAdapter
时,传递 layout
而不是 id
编辑 您必须使用以下内容创建一个 xml 布局,该布局取自您提供的链接:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
>
<TextView android:text="Text" android:id="@+id/listitem_text"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
></TextView>
<ImageView android:id="@+id/listitem_icon"
android:src="@drawable/globe2_32x32"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxWidth="32px"
android:maxHeight="32px"
>
</ImageView>
</LinearLayout>
如果您在布局目录中将其称为 mylistrow.xml
,那么您可以将适配器构造为:
adapter = new MyClickableChannelListAdapter(this, R.layout.mylistrow, channelList);
setListAdapter(adapter);
关于java - 可点击的 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4578390/