我想在我的子视图上将onTouchListener放在我的父View和onLongClickListener上,它看起来像这样
for(int i=0;i<(boardSize*boardSize);i++){
if(i%boardSize==0){
layout=new LinearLayout(MainActivity.this);
layout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
layout.setOrientation(LinearLayout.HORIZONTAL);
parentLayout.addView(layout);
}
imageViews.add(new ImageView(this));
imageViews.get(i).setImageResource(R.drawable.tiles);
imageViews.get(i).setScaleType(ImageView.ScaleType.CENTER_CROP);
imageViews.get(i).setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
PopupMenu popupMenu=new PopupMenu(MainActivity.this , v);
popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch(item.getItemId()){
case R.id.flag:
((ImageView) v).setImageResource(R.drawable.flag_icon);
break;
case R.id.question:
break;
case R.id.clear:
break;
}
return true;
}
});
popupMenu.show();
return false;
}
});
String tileID = "tile_"+i;
int resID = getResources().getIdentifier(tileID, "id", getPackageName());
imageViews.get(i).setId(resID);
layout.addView(imageViews.get(i));
isViewDiscovered[i]=false;
}
parentLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(final View v, final MotionEvent event) {
LinearLayout layout=(LinearLayout)v;
for(int i=0;i<layout.getChildCount();i++){
LinearLayout horizontalLayout=(LinearLayout) layout.getChildAt(i);
for(int j=0;j<horizontalLayout.getChildCount();j++){
ImageView view=(ImageView) horizontalLayout.getChildAt(j);
Rect outRect=new Rect(view.getLeft(),view.getTop(),view.getRight(),view.getBottom());
if(!isViewDiscovered[j+10*i]) {
if (outRect.contains((int) event.getX() - horizontalLayout.getLeft(), (int) event.getY() - horizontalLayout.getTop())) {
view.setImageResource(R.drawable.r1);
} else {
view.setImageResource(R.drawable.tiles);
}
if (event.getAction() == MotionEvent.ACTION_UP && outRect.contains((int) event.getX() - horizontalLayout.getLeft(), (int) event.getY() - horizontalLayout.getTop())) {
view.setImageResource(R.drawable.r2);
isViewDiscovered[j+10*i]=true;
}
}
}
}
return true;
}
});
它没有按预期工作。我只是获得点击输入,但触摸事件不会发生。当我切断clicklistener时,touchListener工作得很好。此外,当我跳入调试器时,当我进入parentLayout.setOnClickListener时,它告诉我parentLayout =没有这样的实例字段:&#39; parentLayout&#39;甚至它在上面定义并且多次使用。 感谢您的帮助