在ViewPagerAdapter上将数据从父片段传递到子片段

时间:2016-07-12 14:41:17

标签: android android-fragments

我有以下片段:

public class VehicleEditFragment extends Fragment {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private SharedPreferences preferences;
    private View myView;
    private ViewPagerAdapter adapter;
    private Vehicle vehicle;
    private int vehicle_id;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        myView = inflater.inflate(R.layout.activity_scrollable_tabs, container, false);
        preferences = getActivity().getSharedPreferences(Config.SHARED_PREF_LOGIN, Context.MODE_PRIVATE);
        Bundle args = this.getArguments();
        vehicle_id = args.getInt("vehicle_id");
        viewPager = (ViewPager) myView.findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) myView.findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        return myView;
    }

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

    }


    private void setupViewPager(ViewPager viewPager) {
        getActivity().setTitle("Vehiculo");
        adapter = new ViewPagerAdapter(getChildFragmentManager());
        adapter.addFrag(new VehicleBasicInfoFragment(), "Datos básicos");
        adapter.addFrag(new VehicleEquipmentServicesFragment(), "Equipamiento y Servicios");
        adapter.addFrag(new VehicleExplanationFragment(), "Descripción");
        adapter.addFrag(new VehicleLocationFragment(), "Localización");
        adapter.addFrag(new VehicleImagesFragment(), "Fotos");
        adapter.addFrag(new VehicleRatesFragment(), "Tarifas");
        adapter.addFrag(new VehicleDisponibilityFragment(), "Disponibilidad");
        viewPager.setAdapter(adapter);
    }



    @Override
    public void onStop() {
        super.onStop();
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

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

        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

    private class FindVehicleInfo extends AsyncTask<String, Void, String> {
        String token = preferences.getString(Config.TOKEN, "");

        @Override
        protected void onPreExecute() {
            //swipeRefreshLayout.setRefreshing(true);
            //toast = Toast.makeText(getActivity().getApplicationContext(), "", Toast.LENGTH_LONG);
        }

        @Override
        protected void onPostExecute(String s){
            if(vehicle.getError() != 0){
                if(vehicle.getError() == Config.JWT_EXPIRED){
                    //logout();
                    Toast.makeText(getActivity().getApplicationContext(),
                            getActivity().getString(R.string.session_expired),
                            Toast.LENGTH_LONG).show();
                }else {
                    //toast.setText(getActivity().getString(R.string.find_pendings_errror));
                   // toast.show();
                }
            }else {
                //setUpAdapter();
            }
            //swipeRefreshLayout.setRefreshing(false);
        }

        @Override
        protected String doInBackground(String... params) {
            vehicle = DBConnect.GetVehicleInfo(token, vehicle_id);
            return "done";
        }
    }
}

我需要的是将Vehicle类的信息传递给我拥有的所有子片段。完美的方法是能够将父母与每个孩子联系起来并从父母那里获得车辆信息。那可能吗?或者有没有其他方法将信息传递给每个孩子?

1 个答案:

答案 0 :(得分:1)

因此,假设Vehicle类是您编写的类,我建议让该类实现Parcelable接口。

然后,由于对象是Parcelable,您可以使用新的实例方法将其传递给Fragment:

public static VehicleBasicInfoFragment NewInstance(Vehicle vehicle) {
   Bundle args = new Bundle();
   args.putParcelable("vehicleKey", vehicle);

   VehicleBasicInfoFragment fragment = new VehicleBasicInfoFragment();
   fragment.setArguments(args);

   return fragment;
}

然后,您可以从onCreate方法中检索该信息:

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

   Vehicle vehicle = getArguments.getExtras().getParcelable("vehicleKey");
}

一旦您更新了子片段以拥有自己的NewInstance方法,就可以像这样更新ViewHolder创建:

adapter.addFrag(VehicleBasicInfoFragment.NewInstance(vehicleObject), "Datos básicos");