从片段内部替换或从ViewPager中删除片段

时间:2015-09-04 06:45:27

标签: android android-fragments android-viewpager

我正在使用ViewPager来创建滑动视图效果。我想知道如何从扩展Fragment的 myFragmentClass 替换viewpager的当前片段。我寻找解决方案但其中大部分都是关于实现用户定义的函数,该函数将使用扩展 FragmentPagerAdapter 的类的 FragmentManager 来替换或删除当前设置的片段。如果您从位于初始化ViewPager的同一活动中的某个UI元素执行此操作,则非常简单。我希望ViewPager中的第一个片段被另一个片段替换,以响应第一个片段中的动作(如按下按钮或其他东西)。

这是我的MainActivity,我正在初始化和扩展FragmentPagerAdapter:

public class MainActivity extends FragmentActivity {

    private ViewPager mViewPager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(new FragmentAdapter(getSupportFragmentManager()));
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });



    }
}

class FragmentAdapter extends FragmentPagerAdapter{


    public FragmentAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment frag = null;
        if(position == 0){
            frag = new MainScreenFragment();
        }
        return frag;
    }

    @Override
    public int getCount() {
        return 1;
    }

}

这是我的第一个片段扩展片段:

public class MainScreenFragment extends Fragment implements View.OnClickListener {

        private static int IMAGE_PIC = 22;
        static int CAMERA_REQUEST = 123;
        TextView mainTextv;
        LinearLayout llContainer;
        Activity activity;
        Context context;
        ImageView camera, gallery,picture,mainLogo;
        public MainScreenFragment(){
            //EMPTY CONSTRUCTOR
        }



        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View v = inflater.inflate(R.layout.mainscreen_fragment, container, false);
            //DoSOMETHING WITH MAIN TEXT HEADING
            camera = (ImageView)v.findViewById(R.id.cameraCapture);
                    camera.setOnClickListener(this);
            mainLogo= (ImageView)v.findViewById(R.id.mainImage);
                    mainLogo.setOnClickListener(this);
            gallery = (ImageView)v.findViewById(R.id.galleryCapture);
                    gallery.setOnClickListener(this);
            picture = (ImageView) v.findViewById(R.id.capturedImageView);
            llContainer = (LinearLayout) v.findViewById(R.id.llSelector);

            return v;

        }


        @Override
        public void onClick(View v) {
            switch(v.getId()){
                case R.id.cameraCapture:
                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

                    startActivityForResult(cameraIntent, CAMERA_REQUEST);

                    break;
                case R.id.galleryCapture:
                    Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(galleryIntent, IMAGE_PIC);

                    break;
                case R.id.mainImage:
                    DisplayMetrics dm = new DisplayMetrics();
                    getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
                    final Dialog d = new Dialog(getActivity());
                    d.requestWindowFeature(Window.FEATURE_NO_TITLE);
                    d.setContentView(R.layout.dialog_picture);
                    d.getWindow().setLayout(dm.widthPixels - 100, dm.heightPixels - 100);
                    final ImageView im = (ImageView) d.findViewById(R.id.imageSelected);
                    Button btnSub = (Button) d.findViewById(R.id.submitBtn);
                    Button btnCancel = (Button) d.findViewById(R.id.btnCancel);
                    btnSub.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //THIS IS THE POINT WHERE I WANT TO REPLACE THE CURRENT FRAGEMENT WITH ANOTHER ONE.
                        }
                    });
                    btnCancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            im.setVisibility(View.GONE);
                            d.dismiss();

                        }
                    });
                    im.setImageBitmap(BitmapFactory.decodeResource(getActivity().getResources(),R.drawable.testing_image_eye));
                    d.show();
                    break;
            }
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if(resultCode == Activity.RESULT_OK){
                if(requestCode == CAMERA_REQUEST){
                    Bundle extras = data.getExtras();
                    try{
                        picture.setVisibility(View.VISIBLE);
                        picture.setImageBitmap((Bitmap)extras.get("data"));
                    }
                    catch(Exception e ){e.printStackTrace();}

                }else if(requestCode == IMAGE_PIC){
                    Toast.makeText(getActivity(),"Image picked",Toast.LENGTH_SHORT).show();
                  try {
                      Uri selectedImage = data.getData();
                      String[] filePathColumn = {MediaStore.Images.Media.DATA};

                      Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);

                      cursor.moveToFirst();
                      int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                      String imgDecodeableString = cursor.getString(columnIndex);
                                cursor.close();

                      picture.setVisibility(View.VISIBLE);
                      picture.setImageBitmap(BitmapFactory.decodeFile(imgDecodeableString));


                  }catch(Exception e ) {
                      e.printStackTrace();
                      Toast.makeText(getActivity(),"Something went wrong! Debug!",Toast.LENGTH_SHORT).show();

                  }
                }
            }
        }
    }

知道如何用firstFragmentClass中的另一个替换当前的Fragment吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

您应该使用getFragmentManager().beginTransaction().replace(int id, Fragment fr).commit();方法而不是onViewCreated()方法调用onCreateView()