将视图放在不同的位置

时间:2017-07-21 19:31:58

标签: android imageview position

我想在更大的Imageview上放置图标(Imageviews)。像这样:

ArrayList<Icon> icons = new ArrayList<Icons>;
for(Icon icon : icons){
   ImageView iv = new ImageView(this);
   iv.setLayoutParams(new LinearLayout.LayoutParams(
                                 LinearLayout.LayoutParams.WRAP_CONTENT,
                                 LinearLayout.LayoutParams.WRAP_CONTENT));
   iv.setImageBitmap(icon.getBitMap());
   iv.setPosition(icon.getX(),icon.getY()); //Thats the line I need to know
   myLayout.addView(iv); 
}

但问题是我无法找到一种方法来提高效率并知道点击了哪个图像视图。

2 个答案:

答案 0 :(得分:1)

要确定点击了哪个视图,请为其应用标记,然后检查通过onClick()传递的视图的标记

ArrayList<Icon> icons = new ArrayList<Icons>;
for(int i = 0; i < icons.size(); i++) {
   Icon icon = icons.get(i);
   ImageView iv = new ImageView(this);
   iv.setTag(i);
   iv.setLayoutParams(new LinearLayout.LayoutParams(
                                 LinearLayout.LayoutParams.WRAP_CONTENT,
                                 LinearLayout.LayoutParams.WRAP_CONTENT));
   iv.setImageBitmap(icon.getBitMap());
   iv.setOnClickListener(new View.OnClickListener({
       @Override
       public void onClick(View view) {
           iconClicked(view);
       }
   });
   myLayout.addView(iv); 
}


public void iconClicked(View view) {
    switch((Integer) view.getTag())
        case 0:
            //...
            break;
        case 1: 
            //...
            break;
        default:
            break;
    }
}

答案 1 :(得分:0)

我找到了解决我的定位问题的方法:

ImageView imageView = (ImageView)findViewById(R.id.imageView);
imageView.setX(xPosition);
imageView.setY(YPosition);

点击了Image的问题,非常好地回答了@Hobo Joe,这个样本!

ArrayList<Icon> icons = new ArrayList<Icons>;
for(int i = 0; i < icons.size(); i++) {
   Icon icon = icons.get(i);
   ImageView iv = new ImageView(this);
   iv.setTag(i);
   iv.setLayoutParams(new LinearLayout.LayoutParams(
                                 LinearLayout.LayoutParams.WRAP_CONTENT,
                                 LinearLayout.LayoutParams.WRAP_CONTENT));
   iv.setImageBitmap(icon.getBitMap());
   iv.setOnClickListener(new View.OnClickListener({
       @Override
       public void onClick(View view) {
           iconClicked(view);
       }
   });
   myLayout.addView(iv); 
}


public void iconClicked(View view) {
    switch((Integer) view.getTag())
        case 0:
            //...
            break;
        case 1: 
            //...
            break;
        default:
            break;
    }
}