I am playing with UI Event Handling, and I have found something that I cannot find the explanation from the Android Dev: I have an ImageView, and a TextView , whenever I touch on the ImageView, the TextView show a message. But the following codes doesn't work:
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);
}
}
And 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>
But when I attach an OnTouchListener on the MyImageView like this, it does work: 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);
}
}
And file MyImageView.java
public class MyImageView extends ImageView {
private TextView textview;
public MyImageView(Context context,TextView textview) {
super(context);
this.textview = textview;
}
}
But as far as I know, the 2 implementation is the same (implement an Event Listener) - do I misunderstand anything ?
Your first implementation forgets to set the listener... call setOnTouchListener(this)
in the MyImageView
constructor and it should work.
For the first case, the right way would be:
MyImageView image = new MyImageView(this, textview);
image.setImageResource(R.drawable.icon);
image.setOnTouchListener(image);
or call setOnTouchListener(this)
inside your MyImageView class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With