OnClickListener不适用于可点击属性

Sci*_*cit 11 android onclicklistener android-relativelayout

所以,我的问题是OnClickListener当我android:clickable="true"进入我的班级时不起作用.

这是MyClassxml代码:

<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>
Run Code Online (Sandbox Code Playgroud)

MyClass.java:

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");
    }
...
...
}
Run Code Online (Sandbox Code Playgroud)

当我设置android:clickable为false 时,它工作正常.我错了什么?

Rom*_*Guy 19

设置OnClickListener将自动将clickable属性设置为true.你展示的代码虽然令人困惑.我的理解是您的MyClass视图是RelativeLayoutXML文件中显示的父视图.

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

只需clickable=true从您的XML中删除即可.


een*_*nto 8

当你这样做:android:clickable="true"你禁用onClickListener(它不合逻辑,但它像那样..).

所以将它设置为"false"或只是从XML文件中删除此行;)


ser*_*tem 5

将ID添加到您的布局:

<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>
Run Code Online (Sandbox Code Playgroud)

然后在java代码中:

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");
    }
...
...
}
Run Code Online (Sandbox Code Playgroud)