android - 在包含布局的 View 上设置 onClickListener 不起作用

标签 android android-layout

我有一个布局,其中包含其他布局。我试图在包含的布局内的 ImageView 上设置 onClikeListener,但它不起作用。但是当我设置可绘制背景时它起作用了。我不知道为什么。这是我的代码:

//custom header
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/sticky_header"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <ImageView
        android:id="@+id/iv_header_close"
        android:layout_width="60dp"
        android:layout_height="55dp"
        android:background="@drawable/big_cross_icon" />
</LinearLayout>

//activity_detail
<?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"
    android:background="#f1f2f6">
    <include
        android:id="@+id/header"
        layout="@layout/custom_header"/>
</RelativeLayout>

//in Activity
View header = findViewById(R.id.header);
iv_header_close = (ImageView)header.findViewById(R.id.iv_header_close);
iv_header_close.setBackgroundDrawable(getResources().getDrawable(R.drawable.big_edit_icon));
iv_header_close.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        finish(); //not working
    }
});

我想知道为什么我可以访问包含的布局中的 subview 但不能设置 OnClickListner。非常感谢:)

最佳答案

像这样创建你的 iv_header_close:

ImageView iv_header_close = (ImageView) findViewById(R.id.iv_header_close);

而不是调用 finish() 尝试调用 YourActivity.this.finish()

发生的事情是,在 ImageView 的 onClick 中,您无权访问您的 Activity ,因此您必须使用 YourActivity.this 访问您的 Activity ,如果你想访问你的 Activity 的方法。

关于android - 在包含布局的 View 上设置 onClickListener 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35005706/

相关文章:

java - getIntent() 返回空指针异常

android - 捕获视频并将其存储在特定位置而不是默认位置

android - TextView 不粘在右上角

android - layout_centerHorizo​​ntal 未居中

java - findViewById 从 Activity 返回 null

android - 无法将自定义选择器添加到 ListView

android - 如何从应用程序移动到动态壁纸预览?

android - 将 GridView 调整为所有屏幕尺寸

java - Android Layout Inflater 不工作?

java - Android EditText 颜色更改会破坏边距