首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >OnClickListener不适用于clickable属性

OnClickListener不适用于clickable属性
EN

Stack Overflow用户
提问于 2011-08-07 17:18:38
回答 5查看 14.5K关注 0票数 12

所以,我的问题是,当我将android:clickable="true"设置到我的类中时,OnClickListener不工作。

这是MyClass xml代码:

代码语言:javascript
复制
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/background"
    android:clickable="true">
...
...
</RelativeLayout>

MyClass.java:

代码语言:javascript
复制
public class MyClass extends RelativeLayout implements OnClickListener {
    public MyClass(Context context) {
        super(context);

        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.book_item, this);
        setOnClickListener(this);
    }

    public void onClick(View v) {
        Log.v("TAG", "Hello");
    }
...
...
}

当我将android:clickable设置为false时,它工作得很好。我做错了什么?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-08-07 17:27:48

设置OnClickListener会自动将clickable属性设置为true。不过,您显示的代码令人困惑。我的理解是,您的MyClass视图是XML文件中显示的RelativeLayout的父级。

如果是这样的话,子RelativeLayout将首先获得触摸事件(因为它是可点击的),但不会对它们做任何事情,因为它没有点击监听器。

只需从XML中删除clickable=true即可。

票数 20
EN

Stack Overflow用户

发布于 2012-08-14 16:00:46

当你这样做的时候:android:clickable="true"你禁用了onClickListener (这不符合逻辑,但就像这样)。

因此,将其设置为"false",或者从XML文件中删除此行;)

票数 11
EN

Stack Overflow用户

发布于 2012-08-15 18:11:51

将id添加到布局中:

代码语言:javascript
复制
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/yourId"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/background"
android:clickable="true">
</RelativeLayout>

然后在java代码中:

代码语言:javascript
复制
public class MyClass extends RelativeLayout implements OnClickListener {
    public MyClass(Context context) {
        super(context);

        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.book_item, this);
        findViewById(R.id.yourId).setOnClickListener(this);
    }

    public void onClick(View v) {
        Log.v("TAG", "Hello");
    }
...
...
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6971836

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档