【发布时间】:2013-12-18 03:38:12
【问题描述】:
我似乎无法从扩展 Fragment 的类中获取图像视图上的 onClick 事件。我在这里做错了什么?我对为 android 开发相对较新..
目前,这段代码给了我一个空指针异常——当我添加 onClickListener 代码时
这是我的代码:
ImageView mImageView = (ImageView) v.findViewById(R.id.option_icon);
mImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
}
});
这些图标被放置在一个列表视图中,该列表视图被放置在一个对话框中:
Dialog的列表视图和按钮:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:id="@+id/preset_list_view"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
<Button
android:id="@+id/dialogButtonOK"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="@string/ok"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_below="@+id/image"/>
</LinearLayout>
列表视图中的项目(图像视图和文本视图):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/option_icon"
android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="@drawable/ic_launcher"
/>
<TextView
android:id="@+id/option_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/image"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="20dp" />
</RelativeLayout>
【问题讨论】:
-
尝试这里发布的解决方案stackoverflow.com/questions/8831043/…,即在您的列表视图RelativeLayout 中添加descendentFocusability,同时检查stackoverflow.com/questions/17502317/…
-
@CSmith 嗯,不走运 =/ 不过感谢您的回复。还有其他建议吗?
-
抱歉,我没有注意“目前,此代码给了我一个空指针异常 - 当我添加 onClickListener 代码时”。我假设您的 findViewById 不起作用,因此我们需要查看更多代码(即变量“v”是什么?)
-
OHHH,我明白了,好吧,现在说得通了。我知道了。谢谢一百万!!!