包裝他們,正如你在我的問題提到爲您的解決方案創建了相同的示例。
我已經使用了半透明區域的兩個圖像。
activity_main.xml中
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rlParent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/triangle" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/triangle2" />
</RelativeLayout>
MainActivity.java
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView imageView, imageView1;
private RelativeLayout rlParent;
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
rlParent = (RelativeLayout) findViewById(R.id.rlParent);
imageView = (ImageView) findViewById(R.id.imageView);
imageView1 = (ImageView) findViewById(R.id.imageView1);
rlParent.setOnTouchListener(new MyTouchListener(rlParent, this));
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageView:
showToast("Image 1 Click");
break;
case R.id.imageView1:
showToast("Image 2 Click");
break;
}
}
private class MyTouchListener implements View.OnTouchListener {
private ViewGroup viewGroup;
private View.OnClickListener onClickListener;
public MyTouchListener(ViewGroup viewGroup, View.OnClickListener onClickListener) {
this.viewGroup = viewGroup;
this.onClickListener = onClickListener;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
for (int pos = 0; pos < viewGroup.getChildCount(); pos++) {
View view = viewGroup.getChildAt(pos);
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
int x = (int) event.getX();
int y = (int) event.getY();
if (bitmap.getPixel(x, y) != Color.TRANSPARENT) {
if (onClickListener != null) {
onClickListener.onClick(view);
break;
}
}
}
break;
}
return true;
}
}
}
您可以檢查下面的截圖來檢查特定圖像點擊,
截圖
我希望它可以幫助你。
什麼是二和四,你是如何初始化它們的? –
我已經初始化它們如下 ImageView two =(ImageView)findViewById(R.id.twoWheeler);和 ImageView four =(ImageView)findViewById(R.id.fourWheeler) – Nbn