getWidth()在onCreateView()中返回0

时间:2013-12-01 13:44:20

标签: android orientation-changes

我开始意图从图库中选择一个图像,然后缩放图像并以幻想方式将ImageView添加到布局中。

我希望在方向更改时重新加载此图像。我在onCreate中设置了setRetainInstance(true)。但是,在方向更改之后,当我尝试通过调用FrameLayout(应该是它的容器)上的getWidth()来获得适当的位图宽度来缩放时,我得到0。

public class NewWallpaper extends Fragment {
    private static final int PICK_BACKGROUND = 1;

    private BitmapFactory.Options bitmapFactoryOptions;

    // Data
    private Uri backgroundURI = null;
    private WeakReference<Bitmap> backgroundBitmap = null;

    // Views
    FrameLayout backgroundContainer;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_new_wallpaper, container, false);

        // BitmapFactory options
        bitmapFactoryOptions = new BitmapFactory.Options();
        bitmapFactoryOptions.inPurgeable = true;

        Button pickBackground = (Button) view.findViewById(R.id.buttonPickBackground);
        pickBackground.setOnClickListener(pickBackgroundListener);

        backgroundContainer = (FrameLayout) view.findViewById(R.id.frameLayoutbackgroundContainer);

        if (backgroundURI != null)
            setBackgroundPreview();

        return view;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setRetainInstance(true);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }


    private Button.OnClickListener pickBackgroundListener = new Button.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");

            startActivityForResult(intent, PICK_BACKGROUND);
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == PICK_BACKGROUND && resultCode == getActivity().RESULT_OK && data != null && data.getData() != null) {
            backgroundURI = data.getData();
            setBackgroundPreview();
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void setBackgroundPreview() {
        try {
            backgroundContainer.removeAllViews();

            Bitmap background = BitmapHelper.loadScaledBitmap(getActivity(), backgroundURI, backgroundContainer.getWidth());

            backgroundBitmap = new WeakReference<Bitmap>(background);

            // returns 0
            int containerWidth = backgroundContainer.getWidth();

            ImageView backgroundView = new ImageView(getActivity());
            backgroundView.setLayoutParams(new LinearLayout.LayoutParams(
                    backgroundContainer.getWidth(),
                    BitmapHelper.calculateHeight(
                            background.getWidth(),
                            background.getHeight(),
                            backgroundContainer.getWidth())
            ));
            backgroundView.setAdjustViewBounds(true);
            backgroundView.setScaleType(ImageView.ScaleType.FIT_XY);
            backgroundView.setImageBitmap(background);

            backgroundContainer.addView(backgroundView);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

我似乎找不到一种方法来改变方向后重新填充视图。有人能告诉我我做错了什么吗?

3 个答案:

答案 0 :(得分:1)

请勿从setBackgroundPreview()致电onCreateView。如果尚未完成创建,则无法测量视图。

请改为setBackgroundPreview()中的onActivityCreated

答案 1 :(得分:1)

如果你想要像素宽度,你应该调用view.getMeasuredWidth()。 getWidth()和getHeight()会给你

LayoutParams.WRAP_CONTENT | LayoutParams.MATCH_PARENT  //constants (1 or 0).

但是,为了确保获得正确的值,请在视图的@onDraw()回调之后调用该方法(以便覆盖它),或者获取viewTreeObserver并等待onGlobalLayout()回调来调用方法。

<强>&LT;&LT;&LT;&LT;&LT;编辑:&gt;&gt;&gt;&gt;&gt;

使用ViewTreeObserver找到一个示例:

ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
  viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
      view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
      viewWidth = mediaGallery.getMeasuredWidth();
      viewHeight = mediaGallery.getMeasuredHeight();
    }
  });
}

在第一次回调后删除监听器确保释放大量进程,因为我们只需要一次测量的params。

答案 2 :(得分:0)

  

在视图实际呈现到屏幕之前,不会定义宽度和高度。   收集自getWidth and getHeight are returning a zero。    另请查看此帖子How do you to retrieve dimensions of a view? Getheight() and Getwidth() always return zero