Android:onTouch()永远不会被调用?

我正在玩UI事件处理,而且我发现了一些我无法从Android Dev中find解释的东西:我有一个ImageView和一个TextView,每当我触摸ImageView,TextView都会显示一条消息。 但是下面的代码不起作用:

public class ShowSomething extends Activity { private LinearLayout ll; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout); final TextView textview = (TextView)findViewById(R.id.textview); MyImageView image = new MyImageView(this, textview); image.setImageResource(R.drawable.icon); ll.addView(image, 48, 48); } } 

和MyImageView.java

 public class MyImageView extends ImageView implements OnTouchListener{ private TextView textview; public MyImageView(Context context,TextView textview) { super(context); this.textview = textview; } @Override public boolean onTouch(View v, MotionEvent event) { textview.setText("Event captured !"); return true; } } 

main.xml中

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linearLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/textview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Holder" /> </LinearLayout> 

但是当我像这样在MyImageView上附加一个OnTouchListener时,它确实有效:File ShowSomething.java

 public class ShowSomething extends Activity { private LinearLayout ll; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout); final TextView textview = (TextView)findViewById(R.id.textview); MyImageView image = new MyImageView(this,textview); image.setImageResource(R.drawable.icon); image.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { textview.setText("Event captured!"); return false; } }); ll.addView(image, 48, 48); } } 

并文件MyImageView.java

 public class MyImageView extends ImageView { private TextView textview; public MyImageView(Context context,TextView textview) { super(context); this.textview = textview; } } 

但据我所知,2实现是相同的(实现事件监听器) – 我误解任何东西?

Solutions Collecting From Web of "Android:onTouch()永远不会被调用?"

对于第一种情况,正确的做法是:

 MyImageView image = new MyImageView(this, textview); image.setImageResource(R.drawable.icon); image.setOnTouchListener(image); 

或者在MyImageView类中调用setOnTouchListener(this)

你的第一个实现忘记设置侦听器…在MyImageView构造函数中调用setOnTouchListener(this) ,它应该工作。