Search code examples
androidapiimageviewandroid-relativelayoutbackwards-compatibility

Moving a View programmatically for api lower than 14


I'm using the getX/getY and setX/setY methods to dynamically change the position of some ImageViews in order to make them follow the finger movements. The problem is that these methods require api level 14 and up. Is there any other way to make my cod compatiple with lower api levels?

Here is some code:

 for (int i = 0; i < num; i++) {
        rel.removeView(finger[i]);
        finger[i].setBackgroundResource(R.drawable.finger);
        try{
            finger[i].setX(e.getX(e.getPointerId(i))-100);
            finger[i].setY(e.getY(e.getPointerId(i))-100);
            rel.addView(finger[i]);
            }catch(Exception ex){
                rel.removeView(finger[i]);
            }
 }

finger[i] are my ImageViews and rel, the RelativeLayout of my xml. num is the number of fingers currently touching the screen.

private ImageView[] finger = new ImageView[10];
private RelativeLayout rel;

Solution

  • For lower APIs you can try setting the margins of the ImageViews:

    RelativeLayout.LayoutParams params = finger[i].getLayoutParams();
    params.leftMargin += i*100;
    params.topMargin += i*100;
    finger[i].setLayoutParams(params);