当图像上发生触摸事件时,我正在尝试添加图像按钮。使用ImageView显示图像。但当我触摸图像时,什么也没发生。此处附加的代码
Quick.java
ImageView myImageView = (ImageView)findViewById(R.id.imgView);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.india_map);
myImageView.setImageBitmap(bitmap);
myImageView.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
ImageButton imgbutton=(ImageButton)findViewById(R.id.imageButton1);
Bitmap image = BitmapFactory.decodeResource(getResources(),R.drawable.image5);
imgbutton.setImageBitmap(image);
imgbutton.setVisibility(View.VISIBLE);
return false;
}
});
activity_quick.xml
<LinearLayout
android:id="@+id/tab2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="5dp" >
<ImageView
android:id="@+id/imgView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:contentDescription="@string/desc"
android:src="@drawable/india_map"/>
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/image5"
android:contentDescription="@string/desc"
android:visibility="invisible" />
</LinearLayout>
请帮我解决这个问题
使用FrameLayout将一个视图置于另一个视图之上。
尝试以下操作:
<FrameLayout
android:id="@+id/tab2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="5dp" >
<ImageView
android:id="@+id/imgView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:contentDescription="@string/desc"
android:src="@drawable/india_map"/>
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/image5"
android:contentDescription="@string/desc"
android:visibility="gone" />
</FrameLayout>
无需在java代码中设置图像位图。您已经在xml中指定了它们。
myImageView.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
ImageButton imgbutton=(ImageButton)findViewById(R.id.imageButton1);
Bitmap image = BitmapFactory.decodeResource(getResources(),R.drawable.image5);
imgbutton.setImageBitmap(null);
imgbutton.setImageBitmap(image);
imgbutton.setVisibility(View.VISIBLE);
return false;
}
});
首先将图像位图设置为null,然后再设置其他位图。
将图像视图设置为可单击。在xml中使用android:clickleable="true"
使用TouchListener有什么特殊的原因吗?(例如>用于处理捏或滑动手势)
如果你考虑的只是"处理图片的点击事件",我认为这是更好的&易于使用OnClickListener而不是OnTouchListener。例如
View iv = findViewById(R.id.imgView));
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ImageButton imgbutton=(ImageButton)findViewById(R.id.imageButton1);
Bitmap image = BitmapFactory.decodeResource(getResources(),R.drawable.image5);
imgbutton.setImageBitmap(image);
imgbutton.setVisibility(View.VISIBLE);
});
你可能会考虑的另一件事是,在主UI线程中解码位图总是不好的,那么考虑使用另一个线程或AsyncTask来处理位图怎么样。