旋转时,ViewPager的Fragment视图丢失,选择了其他片段

时间:2016-02-25 05:32:03

标签: android android-fragments android-viewpager

我使用了viewpager来制作tablayout。有三个标签'照片''视频''文件'。我刚刚完成了“照片”标签的编码。照片选项卡有一个GridView和Button,用于将图像上传到Gridview。单击该按钮时,系统会要求用户选择图库或单击图片并上传图像并将其显示在GridView上,但是当我旋转单元格时,gridview内容将消失。当我关闭应用程序并再次启动它时,以及当我选择文档片段并再次返回到照片片段时,也会发生同样的情况。 我搜索了很多,发现将使用getChildFragmentManager()代替getSupportFragmentManager()。但问题是我的MainActivity是一个Activity而不是Fragment,并且getChildFragmentManager()不能在activity中使用。 这是代码..

// MainFragment.java //从此处设置Viewpager

公共类MainFragment扩展了Fragment {

private TabLayout tabLayout;
private static ViewPager viewPager;
private static FragmentManager fragmentManager;
private View view;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.activity_main, container, false);
    initUI();
    return view;
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    List<Fragment> fragments = getChildFragmentManager().getFragments();
    if (fragments != null) {
        for (Fragment fragment : fragments) {
            fragment.onActivityResult(requestCode, resultCode, data);
        }
    }
}

private void initUI() {
    viewPager = (ViewPager) view.findViewById(R.id.viewpager);
    setupViewPager(viewPager);
}

private void setupViewPager(ViewPager viewPager) {
    fragmentManager = getChildFragmentManager();

    ViewPagerAdapter adapter = new ViewPagerAdapter(fragmentManager);
    viewPager.setAdapter(adapter);
 }}

// PhotoFragment.java

公共类PhotoFragment扩展Fragment {

private FloatingActionButton fabPicture;
private GridView gridView;
private View view;
private Dialog dialog = null;
private int widthofwindow, heightofwindow;
private ImageView btnCameradialog, btnGalleryDialog, btnCamera;
private final int CLICK_PHOTO = 1;
private final int SELECT_PHOTO = 2;
private Uri imageUri;
private String path, picturePath, pathlist;
private List<PictureBeans> pictureDisplayList = null;
private ImageAdapter adapter;


public PhotoFragment() {
    // Required empty public constructor
}

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

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

    initUI();
    setListener();

    return view;
}

private void initUI() {
    btnCamera = (ImageView) view.findViewById(R.id.fabPicture);
    gridView = (GridView) view.findViewById(R.id.grid_view);
    DisplayMetrics metrics = getActivity().getResources().getDisplayMetrics();
    widthofwindow = (int) (metrics.widthPixels * 0.85);
    heightofwindow = (int) (metrics.widthPixels * 1);
    pictureDisplayList = new ArrayList<>();
}

private void setListener() {
    fabPicture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showappwindow();
        }
    });

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent i = new Intent(getActivity(), FullImageActivity.class);
            i.putExtra("id", position);
            i.putExtra("path", pictureDisplayList.get(position).getPicturePath().toString());
            startActivity(i);
        }
    });
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    switch (requestCode) {
        case SELECT_PHOTO:
            if (resultCode == Activity.RESULT_OK) {
                try {
                    imageUri = imageReturnedIntent.getData();
                    path = getRealPathFromURI(getActivity(), imageUri);
                    Log.v("Uri", "" + imageUri);
                    picturePath = path.toString();
                    Log.e("Picture Path in Frag ", "" + picturePath);
                    PictureBeans bean = new PictureBeans();
                    bean.setPicturePath(picturePath);
                    pictureDisplayList.add(bean);
                    Log.e("List size", "" + pictureDisplayList.size());
                    addToAdapter(pictureDisplayList);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            break;

        case CLICK_PHOTO:
            if (resultCode == Activity.RESULT_OK) {


                try {
                    imageUri = imageReturnedIntent.getData();
                    path = getRealPathFromURI(getActivity(), imageUri);
                    picturePath = path.toString();
                    PictureBeans bean = new PictureBeans();
                    bean.setPicturePath(picturePath);
                    pictureDisplayList.add(bean);

                    addToAdapter(pictureDisplayList);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }


            break;
    }
}

private void addToAdapter(List<PictureBeans> pictureDisplayList) {

    adapter = new ImageAdapter(getActivity(), pictureDisplayList);
    gridView.setAdapter(adapter);
}

public String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

public void showappwindow() {
    dialog = new Dialog(getActivity(), R.style.mydialogstyle);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.dialog_photo);
    Window window = dialog.getWindow();
    window.setLayout(widthofwindow, heightofwindow);
    btnCameradialog = (ImageView) dialog.findViewById(R.id.btnCameradialog);
    btnGalleryDialog = (ImageView) dialog.findViewById(R.id.btnGalleryDialog);
    dialog.show();
    btnCameradialog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            getParentFragment().startActivityForResult(cameraIntent, CLICK_PHOTO);
            dialog.dismiss();
        }
    });

    btnGalleryDialog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            photoPickerIntent.setType("image/*");
            getParentFragment().startActivityForResult(photoPickerIntent, SELECT_PHOTO);
            dialog.dismiss();
        }
    });
}}

// ViewPager Adapter

公共类ViewPagerAdapter扩展了FragmentPagerAdapter {

final int PAGE_COUNT = 3;
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private PhotoFragment photoFragment;
private TwoFragment twoFragment;
private ThreeFragment threeFragment;
private String[] titles = new String[]{"Photo", "Video", "Documents"};

public ViewPagerAdapter(FragmentManager manager) {
    super(manager);
}

@Override
public Fragment getItem(int position) {
    Bundle bundle = new Bundle();
    bundle.putInt("request.code", position + 1);
    switch (position) {
        case 0:
            photoFragment = new PhotoFragment();
            return photoFragment;
        case 1:
            twoFragment = new TwoFragment();
            return twoFragment;
        case 2:
            threeFragment = new ThreeFragment();
            return threeFragment;
    }
    return null;
}

@Override
public int getCount() {
    return PAGE_COUNT;
}
@Override
public CharSequence getPageTitle(int position) {
    return titles[position];
}}

0 个答案:

没有答案