我有两种布局,一种LinearLayout
和一种RelativeLayout
。在LinearLayout
我有 10 张图片。当我单击一个图像时,它被添加到RelativeLayout
. 对所有 10 个图像都给出了类似的事件。在 中RelativeLayout
,我已将 a 设置OnTouchListener
为ImageView
从LinearLayout
. 但是我的问题是, onTouch
仅适用于ImageView
最近添加的图像,但是当我尝试触摸以前添加的图像时,它不起作用。我想为相对布局中添加的所有图像添加侦听器。
以下是我迄今为止尝试过的:
for(int i = 0; i < data.length; i++){
image[i] = new ImageView(getApplicationContext());
try{
// int imgID = getResources().getIdentifier(data[i], null, getPackageName());
image[i].setImageResource(data[i]);
}catch(Exception e){
int imgID = getResources().getIdentifier("nia", "drawable", "package");
image[i].setImageResource(imgID);
}
LinearLayout.LayoutParams LEye = new LinearLayout.LayoutParams(
100 , 70);
LEye.leftMargin=20;
image[i].setLayoutParams(LEye);
shapeImageContainer.addView(image[i]); //shapeImageContainer is the Linear Layout
final int c=i;
image[i].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//addContentView( addIcon(), new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT ) );
Toast.makeText(NewProject.this, "Position "+c, Toast.LENGTH_SHORT).show();
rootView.addView(addIcon(c)); //rootView is the Relative layout
}
});
//image[i].setOnTouchListener(MyOnTouchListener);
}
private ImageView addIcon(int c){
item = new ImageView(this);
item.setImageResource(data[c]);
item.setAdjustViewBounds(true);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 60 );
if( mIconIdCounter != 1 ){
params.addRule(RelativeLayout.RIGHT_OF,c-1);
}
item.setLayoutParams( params );
item.setId( mIconIdCounter );
++mIconIdCounter;
item.setOnTouchListener(MyOnTouchListener);
return item;
}
OnTouchListener MyOnTouchListener = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
// scroll.setEnabled(false);
// horizontal.setEnabled(false);
// scroll.setVisibility(View.GONE);
// horizontal.setVisibility(View.GONE);
RelativeLayout.LayoutParams layoutParams2 = (RelativeLayout.LayoutParams) item.getLayoutParams();
switch(event.getActionMasked())
{
case MotionEvent.ACTION_MOVE:
scroll.requestDisallowInterceptTouchEvent(true);
horizontal.requestDisallowInterceptTouchEvent(true);
int x_cord = (int) event.getRawX();
int y_cord = (int) event.getRawY();
//right margin
if (x_cord > windowwidth) {
x_cord = windowwidth-10;
}
// left margin original
if (x_cord <68) {
x_cord = 68;
}
// left margin original
if (y_cord <68) {
y_cord = 68;
}
if (y_cord > windowheight) {
y_cord = windowheight-10;
}
// tv.setText(String.valueOf(y_cord));
layoutParams2.leftMargin = x_cord -60;
layoutParams2.topMargin = y_cord -65;
item.setLayoutParams(layoutParams2);
break;
default:
break;
}
return true;
}
};