gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:36:52 25 4
gpt4 key购买 nike

我有一个布局,其中包含其他布局。我试图在包含的布局内的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com