简体   繁体   中英

Access fragment variable outside of Fragment in view pager

enter image description here

Before reading the question, please refer to image.

I am using viewpager to show the fragment.

Problem

In the fragment, I have used two edittext lets say editText1, editText2 now the problem is how I will get the editText data. I can only get the editText values when user click on next button but the next button is outside of fragment. How do I access the editText outside the fragment.

Before downvoting the question, let me know the reason so that I can improve my question.

Fragment java class

// newInstance constructor for creating fragment with arguments
        public static BpDetails newInstance(int page) {
            BpDetails fragmentFirst = new BpDetails();
            Bundle args = new Bundle();
            args.putInt("someInt", page);
            fragmentFirst.setArguments(args);
            return fragmentFirst;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            page = getArguments().getInt("someInt", 0);
        }


        // Inflate the view for the fragment based on layout XML
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            final View view = inflater.inflate(R.layout.bp_details, container, false);

            Log.i("View ",view.toString());

            Log.i("DOB is ",Long.toString(Constants.dob));


            systolic =(EditText) view.findViewById(R.id.systolic);
            diastolic =(EditText) view.findViewById(R.id.diastolic);


            return view;
        }

ViewPager Activity

vpPager = (ViewPager) findViewById(R.id.view_pager);

        adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
        vpPager.setAdapter(adapterViewPager);

        Fragment fragment=adapterViewPager.getItem(prevPage);

        if (fragment.getClass().equals(BpDetails.class)){
            Log.i("Call ","Yes");
        }

        findViewById(R.id.btn_prev).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // checking for last page
                // if last page home screen will be launched
                int current = getItem(-1);
                if (current!=0)
                    prevPage=current-1;
                if (current < 4) {
                    // move to next screen
                    vpPager.setCurrentItem(current);
                } else {
                    //final reached.
                }

            }
        });

        findViewById(R.id.btn_next).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // checking for last page
                // if last page home screen will be launched
                int current = getItem(+1);



                if (current!=0)
                    prevPage=current-1;

                System.out.println("Prev page "+prevPage);

                if (current < 4) {
                    // move to next screen

                    Fragment prevFragment=adapterViewPager.getItem(prevPage);


                } else {

                    //final reached.
                }
            }
        });


    }

    private int getItem(int i) {
        return vpPager.getCurrentItem() + i;
    }


    public static class MyPagerAdapter extends FragmentPagerAdapter {
        private static int NUM_ITEMS = 4;
        private static int mSelectedPosition;

        public MyPagerAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
            //mSelectedPosition=selectedPosition;
        }

        // Returns total number of pages
        @Override
        public int getCount() {
            return NUM_ITEMS;
        }

        // Returns the fragment to display for that page
        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0: // Fragment # 0 - This will show FirstFragment
                    return BasicDetails.newInstance(0);
                case 1:
                    return BpDetails.newInstance(1);
                case 2:
                    return BslDetails.newInstance(2);
                case 3:
                    return Summary.newInstance(3);

                default:
                    return null;
            }
        }


    }

Create two getters inside your fragment like this.

public String getSystolic(){

    return this.systolic.getText().toString();

    }

public String getDiastolic(){

    return this.diastolic.getText().toString();
    }



     BpDetails fr = (BpDetails)myAdapter.getItem(myViewPager.getCurrentItem());
     String systolicString = fr.getSystolic();

I had a similar issue. .getItem() instantiates a new Fragment , so upon calling myAdapter.getItem(...) you would be getting null for all elements in the Fragment , but not null for the Fragment .

When I fixed this, what I had to do was create another method inside of MyPagerAdapter called getInstantiatedFragment :

public Fragment getInstantiatedFragment(int position)
    {
        return fragments.get(position);
    }

fragments is a new field for the class:

private ArrayList<Fragment> fragments = new ArrayList<>();

I would override getItem() (as you have done already) and change it to:

@Override
    public Fragment getItem(int position)
    {
        switch (position) {
            case 0:
                BasicDetails basicDetails = BasicDetails.newInstance(0);
                fragments.add(basicDetails);
                return basicDetails;
            ...
    }

where you're adding the fragment to fragments before returning, then you would call:

BpDetails fr = (BpDetails)myAdapter.getInstantiatedItem(myViewPager.getCurrentItem());

to get the instance of the created fragment and then call

String systolicString = fr.getSystolic();

if you're using the previous answer's method.

This is so that you can keep track of the instantiated fragments in fragments . I'm sure there are better ways.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM