Tengo MyTrips fragment que contiene ViewPager. Por lo tanto, contiene dos pestañas, es decir, dos fragmentos, uno es ScheduleListFrgment y otro es TripHistoryFragment.

Ahora, cuando reemplazo MyTrips fragment, primero muestra ScheduleListFragment, carga datos del servidor y se muestra en una lista, también carga datos de tripHistory del servidor.

Así que ahora le he dado un evento de clic al elemento de la lista de ScheduleListFragment para que onClick reemplace ScheduleListFragment con PostDetailsFragment.

Ahora, después de presionar hacia atrás desde PostDetailsFragment, se muestra vacío ScheduleListFragment sin lista.

Quiero mostrar la lista cuando el usuario presione desde PostDetailsFragment.

ScheduleListFragment

public class ScheduledTravelFragment extends Fragment implements GetScheduledTripsAsyncTask.GetScheduleTripsCallBack{

    public RecyclerView mRecyclerView_list;
    private ArrayList<Trips> mTripsList;
    private ScheduledTravelAdapter mTripsAdapter;
    public TextView mTextViewData;
    private String mDateTime;
    private SessionData sessionData;

    private RelativeLayout parentLayout;

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


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


        setUpUI(view);


        return view;
    }
    @Override
    public void onStart()
    {
        super.onStart();

        GetScheduledTripsAsyncTask getScheduledTripsAsyncTask = new GetScheduledTripsAsyncTask(getActivity(),parentLayout,ScheduledTravelFragment.this,ScheduledTravelFragment.this);
        getScheduledTripsAsyncTask.execute(mDateTime,sessionData.getString("api_key",""));
    }

    public void setUpUI(View view)
    {

        mRecyclerView_list = (RecyclerView) view.findViewById(R.id.rv_tripList);
        mTextViewData = (TextView) view.findViewById(R.id.textViewData);
        parentLayout = (RelativeLayout) view.findViewById(R.id.parentPanel);

        mTripsList = new ArrayList<Trips>();
        mTripsAdapter = new ScheduledTravelAdapter(getActivity(),mTripsList, ScheduledTravelFragment.this);
        mRecyclerView_list.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView_list.setAdapter(mTripsAdapter);
        mRecyclerView_list.setHasFixedSize(true);
        mRecyclerView_list.setItemViewCacheSize(50);
        mRecyclerView_list.setDrawingCacheEnabled(true);
        mRecyclerView_list.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);

        sessionData = new SessionData(getActivity());
        mDateTime = String.valueOf(CommonUtils.getCurrentDateTime());

    }

    @Override
    public void doPostExecute(ArrayList<Trips> list)
    {
        mTripsList.addAll(list);

        mTripsAdapter.notifyDataChanged();

    }


}

ScheduleListAdapter

public class ScheduledTravelAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {


    private Context context;
    private ArrayList<Trips> list;
    private ScheduledTravelFragment tripListFragment;
    static final int TYPE_LOAD_TRIP = 0, TYPE_LOAD_PROGRESS = 1;
    boolean isLoading = false, isMoreDataAvailable = true;
    TransportListAdapter.OnLoadMoreListener loadMoreListener;

    public ScheduledTravelAdapter(Context context, ArrayList<Trips> list,ScheduledTravelFragment tripListFragment) {
        this.context = context;
        this.list = list;
        this.tripListFragment = tripListFragment;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {

        RecyclerView.ViewHolder viewHolder = null;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        switch (viewType) {

            case TYPE_LOAD_TRIP:
                View v_order_header = inflater.inflate(R.layout.trip_layout, parent, false);
                viewHolder = new TripsHolder(v_order_header);
                break;

        }

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        if (position >= getItemCount() - 1 && isMoreDataAvailable && !isLoading && loadMoreListener != null) {
            isLoading = true;
            loadMoreListener.onLoadMore();
        }

        if (getItemViewType(position) == TYPE_LOAD_TRIP) {
            TripsHolder tripsHolder = (TripsHolder) holder;
            retriveAllTrips(tripsHolder, position);
        } else {
        }

    }

    @Override
    public int getItemViewType(int position) {

        Object obj = list.get(position);

        if (obj instanceof Transport) {
            return TYPE_LOAD_TRIP;
        }

        return super.getItemViewType(position);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }


    public void retriveAllTrips(final TripsHolder holder, int position) {


        final Trips data = (Trips) list.get(position);

        final String newDate = CommonUtils.formateDateFromstring("yyyy-MM-dd HH:mm:ss", "dd MMM, yyyy", data.getmDate());


        holder.tv_date.setText(newDate);
        holder.tv_from.setText(data.getmFrom());
        holder.tv_to.setText(data.getmTo());

        //go to post detail fragment

            holder.lay_row.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Bundle bundle = new Bundle();
                    bundle.putString("pt_id", data.getmPostId());
                    bundle.putString("pt_name", data.getmPostName());
                    bundle.putString("pt_details", data.getmPostDetails());
                    bundle.putString("pt_photo", data.getmImage());
                    bundle.putString("pt_date", data.getmDate());
                    bundle.putString("from", data.getmFrom());
                    bundle.putString("to", data.getmTo());

                    //go to post details screen
                    FragmentManager fragmentManager = tripListFragment.getFragmentManager();
                    PostDetailsFragment fragment = new PostDetailsFragment();
                    fragment.setArguments(bundle);
                    fragmentManager.beginTransaction().replace(R.id.mycontainer, fragment, "POST_DETAILS_FRAGMENT").addToBackStack("O").commit();

                }
            });

 }
    public void notifyDataChanged() {
        notifyDataSetChanged();
        isLoading = false;
    }

}

Editar:

Fragmento de Mis viajes:

public class MyTripsFragment extends Fragment {

    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private CharSequence Titles[]={"Scheduled Travel","Travel History"};
    private int Numboftabs =2;
    private SlidingTabLayout tabs;
    private TabLayout tabLayout;

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

        final Toolbar toolbar = (Toolbar) ((HomeActivity) getActivity()).findViewById(R.id.toolbar);
        ((HomeActivity) getActivity()).setSupportActionBar(toolbar);

        ImageView mLogo = (ImageView) getActivity().findViewById(R.id.imgLogo);
        mLogo.setVisibility(View.GONE);

        TextView title = (TextView) getActivity().findViewById(R.id.textTitle);
        title.setVisibility(View.VISIBLE);
        title.setText(R.string.myTrips);

        mAdapter =  new TabsPagerAdapter(getActivity().getFragmentManager(),Titles,Numboftabs);
        viewPager = (ViewPager)view.findViewById(R.id.pager);

        setupViewPager(viewPager);

        tabLayout = (TabLayout)view.findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        return view;
    }

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

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getFragmentManager());
        adapter.addFragment(new ScheduledTravelFragment(), "Scheduled Travel");
        adapter.addFragment(new TravelHistoryFragment(), "Travel History");
        viewPager.setAdapter(adapter);
    }
    class ViewPagerAdapter extends FragmentStatePagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

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

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

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

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

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

}

Por primera vez, cuando el fragmento creado por el título es mytrips.

enter image description here

En el siguiente fragmento que cambia el texto.`

Barra de herramientas final barra de herramientas = (Barra de herramientas) ((HomeActivity) getActivity ()). findViewById (R.id.toolbar); ((HomeActivity) getActivity ()). SetSupportActionBar (barra de herramientas);

    ImageView mLogo = (ImageView)getActivity().findViewById(R.id.imgLogo);
    mLogo.setVisibility(View.GONE);

    TextView title = (TextView) getActivity().findViewById(R.id.textTitle);
    title.setVisibility(View.VISIBLE);
    title.setText(R.string.tripDetails);`

OnBackedpressed del siguiente fragmento. El logotipo de la aplicación Carry está configurado en el fragmento principal que puedo ver.

enter image description here

0
Sid 22 jun. 2017 a las 09:39

3 respuestas

La mejor respuesta

No debe usar reemplazar. Para su propósito intente agregar.

fragmentManager
.beginTransaction()
.add(R.id.mycontainer, fragment, "POST_DETAILS_FRAGMENT")
.addToBackStack("O")
.commit();

De esta manera, su último fragmento permanecerá en su estado no cambiará y no se creará nuevamente.

No se olvide de hacer clic en su próximo diseño de raíz de fragmento. De esta manera, si hace clic en cualquier lugar, no hará clic en el fragmento inferior.

android:clickable="true"

Tampoco olvides dar fondo a tu próximo fragmento

5
Omid Heshmatinia 22 jun. 2017 a las 07:07

Intenta poner todo esto dentro de Currículum:

GetScheduledTripsAsyncTask getScheduledTripsAsyncTask = new GetScheduledTripsAsyncTask(getActivity(),parentLayout,ScheduledTravelFragment.this,ScheduledTravelFragment.this);
        getScheduledTripsAsyncTask.execute(mDateTime,sessionData.getString("api_key",""));

mTripsList = new ArrayList<Trips>();
        mTripsAdapter = new ScheduledTravelAdapter(getActivity(),mTripsList, ScheduledTravelFragment.this);
        mRecyclerView_list.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView_list.setAdapter(mTripsAdapter);
        mRecyclerView_list.setHasFixedSize(true);
        mRecyclerView_list.setItemViewCacheSize(50);
        mRecyclerView_list.setDrawingCacheEnabled(true);
        mRecyclerView_list.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);

        sessionData = new SessionData(getActivity());
        mDateTime = String.valueOf(CommonUtils.getCurrentDateTime());
0
sumit 22 jun. 2017 a las 06:55

Intente utilizar PostDetailsFragment como hijo de ScheduleListFrgment. Este error nunca surgirá.

GetChildFragmentManager (). beginTransaction () y paso adicional.

2
kunwar nitesh 22 jun. 2017 a las 07:21