所以,我的问题是,当我将android:clickable="true"设置到我的类中时,OnClickListener不工作。
这是MyClass xml代码:
<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");
}
...
...
}当我将android:clickable设置为false时,它工作得很好。我做错了什么?
发布于 2011-08-07 17:27:48
设置OnClickListener会自动将clickable属性设置为true。不过,您显示的代码令人困惑。我的理解是,您的MyClass视图是XML文件中显示的RelativeLayout的父级。
如果是这样的话,子RelativeLayout将首先获得触摸事件(因为它是可点击的),但不会对它们做任何事情,因为它没有点击监听器。
只需从XML中删除clickable=true即可。
发布于 2012-08-14 16:00:46
当你这样做的时候:android:clickable="true"你禁用了onClickListener (这不符合逻辑,但就像这样)。
因此,将其设置为"false",或者从XML文件中删除此行;)
发布于 2012-08-15 18:11:51
将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>然后在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");
}
...
...
}https://stackoverflow.com/questions/6971836
复制相似问题