我有兩個佈局,一個LinearLayout
和一個RelativeLayout
。在LinearLayout
我有10個圖像。當我點擊一張圖片時,它會被添加到RelativeLayout
。所有10幅圖像都有類似的事件。在RelativeLayout
中,我已將OnTouchListener
設置爲從LinearLayout
添加的ImageView
。但我的問題是,onTouch
只適用於最近添加的ImageView
,但當我嘗試觸摸以前添加的圖像時,它不起作用。我想爲在相對佈局中添加的所有圖像添加偵聽器。如何爲動態創建的視圖設置OnTouchListener?
下面是我到目前爲止已經試過:
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;
}
};
發佈您的佈局XML文件 – 2013-03-08 08:23:03