android - 如何在 FragmentStatePagerAdapter 中动态添加页面

标签 android fragmentstatepageradapter

我知道这个问题被问过很多次,但经过多次研究后我没有得到答案。 在我的主要 Activity 中,我有一个 View 寻呼机,并为此设置了一个适配器:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
ViewPager mPager;
    PagerAdapter mPagerAdapter;

    mPager = (ViewPager) findViewById(R.id.pager);
    mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
    mPager.setAdapter(mPagerAdapter);
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    String tag = "onActivityResult";
    String msg = "omad";
    String timeStamp;
    Bitmap reducedImage;
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();//content://media/external/images/media/40596

            selectedImagePath = getPath(selectedImageUri);// /storage/emulated/0/DCIM/Camera/IMG_20131022_192859.jpg
            //reducedImage = reduceImageSize(selectedImagePath);
            Bitmap img = BitmapFactory.decodeFile(selectedImagePath);

            File Images = new File(MainActivity.root + File.separator + "Images");
            String[] Image = Images.list();
            int ImageCount = Image.length;
            try {
                FileOutputStream fos = new FileOutputStream(new File(root + File.separator +
                        "/Images" + File.separator + String.valueOf(ImageCount) + ".jpg"));
                img.compress(Bitmap.CompressFormat.JPEG, 90, fos);
                fos.flush();
                fos.close();
            } catch (IOException e) {
                Log.e("onActivityResult", e.getMessage());
            }
        }
    }

    NUM_PAGES += 1;
        ScreenSlidePagerAdapter test = new  ScreenSlidePagerAdapter(getSupportFragmentManager());
         test.notifyDataSetChanged();
}

我的主要 Activity 中有适配器类,如私有(private)类:

private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
        super(fm);
@Override
    public Fragment getItem(int position) {
        Log.v("adapter", "getitem" + String.valueOf(position));
        return ScreenSlidePageFragment.create(position);
    }
@Override
    public int getCount() {
        Log.v("adapter", "getcount" + String.valueOf(NUM_PAGES));
        return num_pages;
    }

最后我有一个 fragment 类,它为 View 寻呼机中的每个页面扩充我的布局。它有 ImageView 和文本以及......:

public class ScreenSlidePageFragment extends Fragment {

public static final String ARG_PAGE = "page";
private int mPageNumber;
private Context mContext;
private int Cimage;
private ArrayList<Uri> imageUri;

public static ScreenSlidePageFragment create(int pageNumber){
    ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_PAGE, pageNumber);
    fragment.setArguments(args);
    return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mPageNumber = getArguments().getInt(ARG_PAGE);

    imageUri = new ArrayList<Uri>();
             ...
    // image uri get uri of image that saved in directory of app
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // Inflate the layout containing a title and body text.
    //mContext = getActivity();
    ViewGroup rootView = (ViewGroup) inflater
            .inflate(R.layout.fragment_screen_slide_page, container, false);

    // Set the title view to show the page number.
    //View v;
    ImageView imageView;
    //if(convertView == null){
    /*LayoutInflater li = LayoutInflater.from(mContext) ;
    v = li.inflate(R.layout.imagetext, null);*/
    rootView.setId(mPageNumber);
    Button button = (Button) rootView.findViewById(R.id.ImageSetting);
    button.setId(mPageNumber);
    String title = MainActivity.imageSetting.getString(String.valueOf(mPageNumber), "default");
    TextView tv = (TextView) rootView.findViewById(R.id.ImageText);
    tv.setText(title);
    imageView = (ImageView) rootView.findViewById(R.id.image);  //imageView = new ImageView(mContext);
    SetLayoutSize(mPageNumber);
    imageView.setLayoutParams(new RelativeLayout.LayoutParams(layoutWidth, layoutHeight));
    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
    imageView.setPadding(30, 50, 70, 30);
    //imageView.setImageResource(mThumbIds[position]);
        //imageView.setImageURI(imageUri.get(position));
    BitmapFactory.Options option = new BitmapFactory.Options();
    option.inSampleSize = 4; 
    Bitmap bmp = BitmapFactory.decodeFile(imageUri.get(mPageNumber).getPath() , option);
    imageView.setImageBitmap(bmp);

    /*((TextView) rootView.findViewById(android.R.id.text1)).setText(
            getString(R.string.title_template_step, mPageNumber + 1));*/

    return rootView;
}

// this method is not very important

private void SetLayoutSize(int position){
    BitmapFactory.Options option = new BitmapFactory.Options();
    option.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(imageUri.get(position).getPath(), option);
    float scale = (float) ((float) ((double)option.outHeight) / ((double)option.outWidth));
    //Log.v("reduceimage", String.valueOf(imagetemp.getWidth()) + " * " + String.valueOf(imagetemp.getHeight()));
    //Log.v("scale", String.valueOf(scale));
    layoutWidth = MainActivity.display.getWidth();
    layoutHeight = MainActivity.display.getHeight();
    layoutHeight = (int) ( layoutWidth * scale);
    //Log.v("size", String.valueOf(width) + " * " + String.valueOf(height));
    //Bitmap imagebmp = BitmapFactory.decodeFile(path);
 }

这是每个 fragment 的布局:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/content"
>

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

<ImageView 
    android:id="@+id/image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</ImageView>

<TextView 
    android:id="@+id/ImageText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal" />

<Button
    android:id="@+id/ImageSetting"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:onClick="SettingButton"
    android:background="@drawable/ic_menu_moreoverflow_normal_holo_light" />

 </RelativeLayout>
 </ScrollView>

在我的主要 Activity 中,我有一个从图库中获取图像并保存在目录中的按钮。我应该在 onActivityResult 中更新我的适配器,但我收到此错误:

02-03 19:30:21.567: E/AndroidRuntime(3407): java.lang.IllegalStateException: 应用程序的 PagerAdapter 在没有调用 PagerAdapter#notifyDataSetChanged 的​​情况下更改了适配器的内容!预期的适配器项目数:1,找到:2 Pager id:com.sober.secret:id/pager Pager 类:类 android.support.v4.view.ViewPager 有问题的适配器:类 com.example.test.MainActivity$ScreenSlidePagerAdapter

但在应用程序崩溃后,我的图像可以正确显示。 我尝试了 notifyDataSetChanged() 但没有成功,我尝试了 stackoverflow 中的任何解决方案。

最佳答案

调用mPagerAdapter.notifyDataSetChanged()NUM_PAGES += 1; 之后

关于android - 如何在 FragmentStatePagerAdapter 中动态添加页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21532081/

相关文章:

android - 基于 ionic 的游戏服务测量问题

android - 无法使用 fragment 播放多个视频

android - 如何在 MPAndroidChart 中添加 float x 和 float y 值

android - 类不是 View android.support.v4.app.Fragment

Android - 启动画面的淡出动画

android - 无法实现 notifyDataSetChanged()

android - 从 FragmentStatePagerAdapter 动态添加/删除页面

java - GPS 设置为开启且应用程序在首次启动时崩溃

java - 使用 fragmentstatepageradapter 的 nullpointerexception

java - 如何在 FragmentStatePagerAdapter 中循环(从最后一个 fragment 到第一个 fragment )