我正在玩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实现是相同的(实现事件监听器) – 我是否误解了什么?