如何在下一个片段的背面显示片段中的列表?

时间:2017-06-22 06:39:14

标签: java android android-fragments arraylist onbackpressed

我的MyTrips fragment包含ViewPager。因此它包含两个选项卡,即两个片段,一个是ScheduleListFrgment,另一个是TripHistoryFragment

现在当我替换MyTrips fragment它首先显示ScheduleListFragment,从服务器加载数据并在列表中显示时,它还从服务器加载tripHistory的数据。

现在我已将点击事件发送到ScheduleListFragment的列表项,因此onClickScheduleListFragment替换为PostDetailsFragment

现在,在我从PostDetailsFragment返回后,它显示空ScheduleListFragment,没有列表。

我想在用户从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;
    }

}

编辑:

MyTrips frgament:

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);
        }
    }

}

第一次片段创建的标题是mytrips。

enter image description here

关于下一个片段更改文本。

最终工具栏工具栏=(工具栏)((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.tripDetails);`

下一个片段的OnBackpress。在我看到的主要片段上设置了应用程序徽标。

enter image description here

3 个答案:

答案 0 :(得分:4)

你不应该使用替换。为了您的目的,请尝试添加。

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

这样,你的最后一个片段保持其状态不会改变,也不会再次创建。

不要忘记让您的下一个片段根布局可点击。这样,如果您点击任何地方,它将不会点击底部片段。

android:clickable="true"

另外,不要忘记为下一个片段提供背景信息

答案 1 :(得分:2)

尝试使用PostDetailsFragment作为ScheduleListFrgment的子级。 这个bug永远不会出现。

getChildFragmentManager()。beginTransaction()和进一步的步骤。

答案 2 :(得分:0)

尝试将所有内容放在onResume:

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());