我开始打算从图库中选择图像,然后缩放图像并将其动态地添加到布局中。
我希望此图像在方向更改时重新加载。我在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();
}
}
}
我似乎找不到改变方向后重新填充视图的方法。有人可以告诉我我在做什么错吗?
最佳答案
不要从setBackgroundPreview()
呼叫onCreateView
。如果尚未完成创建视图,则无法测量。
改为在setBackgroundPreview()
中调用onActivityCreated
。