Android:在VerticalViewPager中的ImageView上定位EditText

时间:2014-05-02 12:36:12

标签: android android-edittext android-imageview

我有3个VerticalViewPagers彼此相邻。每个视图寻呼机仅包含图像。这是一个例子:

3 vertical view pagers

当用户点击图片时,我需要制作一个EditText。 EditText必须位于每个图像的精确位置。所以我需要获取图像的位置,添加一些常量并使EditText。怎么做?

注意:我尝试了getLocationOnScreen,对于最左边的图像,我得到了[0,50],当我为EditText设置margin top = 50和left = 0时,它位于图像上方。

夸大物品:

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>

1 个答案:

答案 0 :(得分:1)

您还必须将任务栏高度计算在内,因为getLocationOnScreen是布局位于任务栏下方的位置。在屏幕上定位对象时,应用程序布局的左上角为[0,0],但它不是整个屏幕的[0,0]点,因为应用程序布局从任务栏下方开始。 getLocationOnScreen中的点[0,0]位于整个屏幕的左上角,因此您将获得由任务栏高度稍微移动的坐标。 因此,在定位EditText时,只需将任务栏高度添加到y坐标,就可以了。