OnClickListener doesn't work with clickable attribute

Viewed 15110

So, my problem is that OnClickListener doesn't work when I set android:clickable="true" into my class.

This is MyClass xml code:

<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:

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");
    }
...
...
}

It works fine when I set android:clickable to false. What do I wrong?

5 Answers

Instead of implementing OnClickListener to the whole class, you can set OnClickListener to each of the elements after filtering them if there are only few elements to do actions.

TextView textLogin = findViewById(R.id.textLogin);

textLogin.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Log.i("click", "textLoginClicked.");
    }
});

Else you should state that the elements you are going to set OnClickListener like,

textLogin.setOnClickListener(this);

Then you can use,

@Override
public void onClick(View view) {
    if (view.getId() == R.id.textLogin) {
        Log.i("Click", "Login clicked.");
    }
}
Related