Question

I have 3 VerticalViewPagers next to each other. Each view pager contains only images. Here's example:

3 vertical view pagers

when user clicks on the image, I need to make an EditText. The EditText has to be on an exact spot for each image. So I need to get the position of the image, add some constant and make there a EditText. How to do this?

Note: I tried getLocationOnScreen, for the leftmost image, i got [0,50] back and when I set margin top = 50 and left = 0 for the EditText, it was above the image.

Inflating the items:

public Object instantiateItem(ViewGroup collection, final int position) {
    LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View rootView = layoutInflater.inflate(R.layout.item_layout, null);
    final ImageView imageView = (ImageView) rootView.findViewById(R.id.item);          
    final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

    collection.addView(rootView, 0);

    rootView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int[] pos = new int[2];
            imageView.getLocationOnScreen(pos);

            params.leftMargin = coordinates.get(0).first;
            params.topMargin = coordinates.get(0).second;
            EditText editText = new EditText(context);
            editText.setLayoutParams(params);
            ((RelativeLayout) rootView).addView(editText);
            }
        }
    });

    return rootView;

item_layout.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/item_relative_layout"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/item"
        android:contentDescription="@string/imageContent" />

</RelativeLayout>
Was it helpful?

Solution

You must also take taskbar height into calculation, since the getLocationOnScreen is the location when the layout is below the taskbar. When positioning an object on a screen, the top left corner of the application´s layout is [0,0], but it is not the [0,0] point of the whole screen, because the application layout starts below the taskbar. The point [0,0] in the getLocationOnScreen lays in the top left corner of the whole screen so you will get the coordinates slightly moved by the taskbar height. So when positioning your EditText, just add the taskbar height to the y-coordinate and you should be good.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top