【问题标题】:onClick on an imageview within a listview within a dialogonClick 在对话框中的列表视图中的图像视图
【发布时间】: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,我明白了,好吧,现在说得通了。我知道了。谢谢一百万!!!

标签: java android


【解决方案1】:

一定是你试图在 v 所指的范围之外找到它的 ImageView。

如果图像视图在列表视图中,那么您应该从适配器中添加 onClickListener

【讨论】:

    【解决方案2】:

    您尝试查找的imageView 无法从v 访问。如果 imageView 在主布局中,则使用findViewById,而不使用v,否则先膨胀view,然后使用view.findViewById

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多