仍然无法在Fragment中获得图像大小

时间:2014-10-30 13:12:27

标签: android android-fragments

我已尝试thisthis以及其他任何其他内容。但它总是返回0.或者我会错过什么?

这是我的代码:

@SuppressLint("NewApi")
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_photo_editor, container, false);

        img = (ImageView) rootView.findViewById(R.id.photo_editor_img);
        watermark = (ImageView) rootView.findViewById(R.id.photo_editor_watermark);

        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();

        if (android.os.Build.VERSION.SDK_INT >= 13){
            Point size = new Point();
            display.getSize(size);
            screenWidth = size.x;
        }
        else screenWidth = display.getWidth();

        ViewTreeObserver vto = watermark.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                watermarkWidth = watermark.getWidth();
                watermarkHeight = watermark.getHeight();
            }
        });

        vto = img.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                scale = (float) (img.getWidth()/screenWidth);
            }
        });

        return rootView;
    }

我已尝试在onResumeonActivityCreated中替换这些代码,但仍返回0.

这是我的xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/photo_editor_root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black" >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true" >

        <ImageView android:id="@+id/photo_editor_img"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:src="@drawable/bg" />

        <ImageView  android:id="@+id/photo_editor_watermark"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|left"
            android:layout_margin="5dp"
            android:src="@drawable/watermark"/>

    </FrameLayout>

</RelativeLayout>

0 个答案:

没有答案