了解并实现OnSizeChanged以获取ImageView的宽度和高度

时间:2014-02-05 20:06:42

标签: android android-layout android-imageview android-view method-overriding

所以我有一个我在xml中声明的ImageView。

class.xml

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

    <ImageView
        android:id="@+id/confirmationView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentTop="true"
        />

</RelativeLayout>

我的Java文件看起来像。

MyClass.java

public class MyClass extends Activity{

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_confirmation);
        imageView = (ImageView) findViewById(R.id.confirmationView);

        }
}

现在当我尝试imageView.getWidth()imageView.getHeight()时,它总是让我回归零。 所以我在考虑使用here中的protected void onSizeChanged (int w, int h, int oldw, int oldh)。但我不确定这是否是正确的方法。

如果是,那么我应该如何在我的代码结构中实现它。我的类已经扩展了一个Activity,因此不确定如何实现onSizeChanged。

我也尝试过做

ViewTreeObserver vto = confirmationView.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                imageViewSurfaceWidth = imageView.getWidth();
                imageViewSurfaceHeight = imageView.getHeight();
            }

        });

但这对我也不起作用。 如何获得imageView宽度和高度。

2 个答案:

答案 0 :(得分:1)

您可以使用onSizeChange方法,这样您就应该编写自定义ImageView并覆盖onSizeChange。在这种方法中,将提供高度和宽度。

但是注意,这种方法不会在活动中的onCreate()之前被调用。

我相信你可以用这种方式获得高度和宽度:

imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            imageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            imageViewSurfaceWidth = imageView.getWidth();
            imageViewSurfaceHeight = imageView.getHeight();
            Log.i("activity", "width = "+imageViewSurfaceWidth+", height = "+imageViewSurfaceHeight);
        }
    });

我长期以这种方式使用这种方式,效果很好。

你说这不起作用,我认为不应该发生,也许你应该记录onGlobalLayout()中的高度和宽度,看看有什么不对。

答案 1 :(得分:-1)

我在主要活动中使用它:

@Override
public void onWindowFocusChanged(boolean hasFocus) {

 super.onWindowFocusChanged(hasFocus);
main_width=main_view.getWidth();
main_height=main_view.getHeight();


}

其中main_view是你的imageView。

相关问题