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

前端之家收集整理的这篇文章主要介绍了Android:onTouch()永远不会被调用?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在玩UI事件处理,我找到了一些我无法从 Android Dev找到解释的东西:我有一个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时,它确实有效:
文件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);

 } 

}

并提交MyImageView.java文件

public class MyImageView extends ImageView { 


 private TextView textview;

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


}

但据我所知,2实现是相同的(实现事件监听器) – 我是否误解了什么?

解决方法

对于第一种情况,正确的方法是:
MyImageView image = new MyImageView(this,textview);
image.setImageResource(R.drawable.icon);
image.setOnTouchListener(image);

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

猜你在找的Android相关文章