Android测量imageview

时间:2015-03-16 18:12:24

标签: android measure adjustviewbounds

我需要测量ImageView的宽度,但是当我在设置后测量它时 在ImageView上的android:adjustViewBounds,measuredWidth不正确... 我做错了什么,我该如何解决这个问题?

我的布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/lines2"
android:orientation="vertical"
android:weightSum="917">
<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="143">
    <RelativeLayout
        android:id="@+id/rectangleLayout"
        android:background="@drawable/customborder"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <ImageView
        android:id="@+id/circle"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:background="@drawable/circle" 
        android:src="@drawable/circle" 
        />
</RelativeLayout>

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        view = inflater.Inflate (Resource.Layout.pager1Fragment, container, false);

        rectangleLayout = view.FindViewById<ViewGroup> (Resource.Id.rectangleLayout);
        circle = view.FindViewById<ImageView> (Resource.Id.circle);
        circle.Measure ( Android.Views.View.MeasureSpec.MakeMeasureSpec(0, MeasureSpecMode.Unspecified),
            Android.Views.View.MeasureSpec.MakeMeasureSpec(0, MeasureSpecMode.Unspecified));

        Initialize ();

        return view;
    }


    public void Initialize ()
    {
        var rectanglePadding = (int)((double)circle.MeasuredWidth / 2d);
        //measuredWidth is wrong when adjustviewbounds is set

        Console.WriteLine ("padding " + rectanglePadding);

        RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams (RelativeLayout.LayoutParams.MatchParent, RelativeLayout.LayoutParams.MatchParent);
        p.LeftMargin = rectanglePadding;

        rectangleLayout.LayoutParameters = p;

    }

1 个答案:

答案 0 :(得分:0)

确保在创建片段时尽快获取View。

    ImageView Example = (ImageView) parentview.findViewById(R.id.Example);

    Example.getViewTreeObserver().addOnGlobalLayoutListener(
            new ViewTreeObserver.OnGlobalLayoutListener() {
                @SuppressWarnings("deprecation")
                @Override
                public void onGlobalLayout() {
                    Example.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    int width = Example.getWidth() <--- this gives you width.
                }
            });

只需将代码转换为该代码即可。