【问题标题】:get image view position with wrap contant drawable image使用包装内容可绘制图像获取图像视图位置
【发布时间】:2014-10-08 06:36:40
【问题描述】:

我在获取图像视图顶部和左侧位置时遇到问题。

我的图像视图设置在相对布局的中心。 当我使用 getleft()getTop() 时,我的结果是 0 和 0。

我的布局文件是:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:scaleType="center"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

这对我来说真的很紧急。

我的问题:

我编写了一个用于移动和缩放图像视图的代码,该代码可以正常工作,但是在第一次单击时,图像视图位置更改为 0、0,我想获取默认位置以防止在第一次单击时发生更改。

【问题讨论】:

  • 向我们展示您当前的代码?你什么时候打电话给getLeft()getTop()
  • 我通过 id 定义了我的图像视图并想要 Toast 它的位置,我怎样才能在 api 级别 8 上烤图像视图位置?
  • 你在 onCreate 中调用 getLeft()getTop() 吗?
  • 是的,当调用 getTop() 和 getLeft() 我看到 0 , 0 但我的图像设置在屏幕中心和 0, 0 不正确

标签: android image view get position


【解决方案1】:

不确定我是否明白你的意思,但你可以试试:

ImageView img = (ImageView) findViewById(R.id.image_view);
img.getViewTreeObserver().addOnGlobalLayoutListener(
            new ViewTreeObserver.OnGlobalLayoutListener(){

                @Override
                public void onGlobalLayout() {

                    int left = img.getLeft();
                    int top = img.getTop();
                    //Toast the height and top...
                }

            });

由于图像不会在onCreate 中渲染到屏幕上,因此当您调用getLeft()getTop() 时,您将始终得到0

更多解释here

编辑

设置imageview的布局宽高为wrap_content

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:scaleType="center"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

【讨论】:

  • 谢谢,但我的问题仍然存在,我的图像视图位于屏幕中心但左侧和顶部返回零..
  • android:layout_width="fill_parent" android:layout_height="fill_parent" 您的布局代码显示为fill_parent,请尝试更改为wrap_content
【解决方案2】:

int location[]=new int[2];

rlBoard.getLocationOnScreen(位置);

您也可以使用 imageview 的 getX 和 getY 方法,但此方法适用于 api 11

【讨论】:

  • 谢谢 能描述一下这段代码吗?我不使用它!
  • rlBoard 是相对布局对象,位置是整数数组,getLocatiOnScreen 方法用屏幕上的相对布局中心填充数组
  • 再次感谢,我的问题仍然存在!我使用 api 8 并且无法在运行时获取图像视图对象位置... :(
猜你喜欢
  • 1970-01-01
  • 2013-01-20
  • 2018-05-27
  • 1970-01-01
  • 2015-06-17
  • 1970-01-01
  • 1970-01-01
  • 2017-07-01
  • 1970-01-01
相关资源
最近更新 更多