回到主Fragment实例后,碎片不会被FragmentStatePagerAdapter重新创建

时间:2013-12-08 08:36:34

标签: android android-fragments android-viewpager fragmentstatepageradapter

SCOPE

我正在为我的大学节目申请,该节目显示4个特定固定日期的活动。 我有一个main_activity,它有一个linearlayout,每个片段都显示在其上。现在我有一个片段“ ScheduleFragment ”。

ScheduleFragment包含一个ViewPager和一个FragmentStatePagerAdapter,可以切换4个日期。

ViewPager有4个页面代表4个日期,这4个页面来自4个相同片段的引用,即“ ScheduleListSubFragment

从这里用户选择一个事件并可以查看“ EventDescriptionFragment ”中包含的eventDescription

问题

流程顺利。用户遇到ScheduleFragment,然后切换到适当的日期并选择一个事件。

现在,当他从 EventDescriptionFragment 返回到 ScheduleFragment 时(稍后我将告诉我这样做),ViewPager显示空白视图。当我们滑动到下一个日期时,下一个日期的事件就会到来,我们将刷回上一个日期,之前日期的事件又回来了。

我调试了我的应用程序,并且知道当我们返回 ScheduleFragment 时,viewpager不会为 ScheduleListSubFragment 创建新的片段实例,除非我滚动viewpager。< / p>

所以,我认为ViewPager可以启用用户正在查看的特定引用( ScheduleListSubFragment )。

我如何回到ScheduleFragment ? 我在main_activity中创建了一个堆栈。当用户选择一个事件时,我将 ScheduleFragment 的当前引用推送到堆栈中。当按下后退时,我弹出该引用并将其放在屏幕上。

CODE *的 ScheduleFragment *             import com.Nit_kkr.updates.app.adapters.ScheduleFragmentAdapter;             import com.viewpagerindicator.PageIndicator;             import com.viewpagerindicator.TitlePageIndicator;             import com.viewpagerindicator.TitlePageIndicator.IndicatorStyle;

        import android.os.Bundle;
        import android.support.v4.app.Fragment;
        import android.support.v4.view.ViewPager;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.TextView;
        import android.widget.Toast;

        public class ScheduleFragment extends Fragment{
            ScheduleFragmentAdapter mAdapter;
            ViewPager mPager;
            PageIndicator mIndicator;
            TitlePageIndicator indicator;




            @Override
            public void onViewStateRestored(Bundle savedInstanceState) {
        //      Toast.makeText(getActivity(), " onViewStateRestored()", Toast.LENGTH_SHORT).show();
                super.onViewStateRestored(savedInstanceState);
            }

            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                mAdapter = new ScheduleFragmentAdapter(getActivity().getSupportFragmentManager());
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
                View v = inflater.inflate(R.layout.scheduled_list, null);
                prepareSlidingPager(v);

                return v;
            }

            private void prepareSlidingPager(View v)
            {

                    mPager = (ViewPager)v.findViewById(R.id.pager);

                    mPager.setOffscreenPageLimit(4);
                    mPager.setAdapter(mAdapter);

                    mIndicator = (TitlePageIndicator)v.findViewById(R.id.indicator);
                    indicator = (TitlePageIndicator) mIndicator;
                    mIndicator.setViewPager(mPager);

                    final float density = getResources().getDisplayMetrics().density;
                    indicator.setBackgroundColor(0x18AF0000);
                    indicator.setFooterColor(0xFFAA2222);

                    //indicator.setFooterColor(0xFFAA33);

                    indicator.setFooterLineHeight(2 * density); //1dp
                    indicator.setFooterIndicatorHeight(3 * density); //3dp
                    indicator.setFooterIndicatorStyle(IndicatorStyle.Underline);

                    indicator.setTextColor(0xAA000000);
                    indicator.setSelectedColor(0xFF000000);
                    indicator.setSelectedBold(true);
            }


            public static ScheduleFragment newInstance()
            {
                ScheduleFragment frag = new ScheduleFragment();
                return frag;
            }
        }

ScheduleListSubFragment:

            public class ScheduleListSubFragment extends Fragment implements OnItemClickListener{

                long startDate;
                long endDate;


                private ListView eventlist;
                private listadapter adapter;
                private List events;
                private MyDB db;



                @Override
                public void onAttach(Activity activity) {
                    Toast.makeText(getActivity(), " onAttatch()------------------sublist schedule", Toast.LENGTH_SHORT).show();
                    super.onAttach(activity);
                }

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

                    db=new MyDB(this.getActivity());

                    Toast.makeText(getActivity(), " onCreate()------------------sublist schedule", Toast.LENGTH_SHORT).show();

                }

                @Override
                public View onCreateView(LayoutInflater inflater, ViewGroup container,
                        Bundle savedInstanceState) {

                    //Toast.makeText(getActivity(), " onCreateView()------------------sublist schedule", Toast.LENGTH_SHORT).show();

                    View v = inflater.inflate(R.layout.eventslist_subfragment_layout, null);

                    eventlist=(ListView)v.findViewById(R.id.Event_list);
                    eventlist.setOnItemClickListener(this);

                    fetcheventdata(getArguments().getLong("start_time"), getArguments().getLong("end_time"));
                    return v;

                }

                public static ScheduleListSubFragment newInstance(long starttime, long endtime)
                {
                    ScheduleListSubFragment frag = new ScheduleListSubFragment();
                    Bundle bundle = new Bundle();

                    bundle.putLong("start_time", starttime);
                    bundle.putLong("end_time", endtime);
                    frag.setArguments(bundle);

                    return frag;
                }



                 private void fetcheventdata(long starttime, long endtime)
                    {

                        db.open();
                        events=db.getEvents_bycategory_bytime(null, starttime, endtime);
                        db.close();
                        if(events!=null)
                        {
                        adapter=new listadapter(getActivity(), android.R.layout.simple_expandable_list_item_1, events);
                        eventlist.setAdapter(adapter);

                        adapter.notifyDataSetChanged();
                        }
                        else
                            Toast.makeText(getActivity(), "No Events Yet", Toast.LENGTH_LONG);

                        //Toast.makeText(getActivity(), events.size(), Toast.LENGTH_LONG).show();



                    }


                 private class listadapter extends ArrayAdapter<Event>
                    {
                        private List items;

                        public listadapter(Context context, int textViewResourceId,
                                List objects){
                            super(context, textViewResourceId, objects);
                            items=new ArrayList();
                            items=objects;

                        }

                        @Override
                        public View getView(int position, View convertView, ViewGroup parent) {

                            View v=convertView;

                            if(v==null)
                            {
                                LayoutInflater vi=(LayoutInflater)getActivity().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
                                v=vi.inflate(R.layout.upcominglist, null);

                            }

                            Event event=(Event)items.get(position);
                            if(event!=null)
                            {
                                TextView name=(TextView)v.findViewById(R.id.Name);
                                TextView venue=(TextView)v.findViewById(R.id.Venue);
                                TextView time=(TextView)v.findViewById(R.id.time);


                                name.setTypeface(Utils.getHeroFace(getActivity().getAssets()));
                                venue.setTypeface(Utils.getHeroFace(getActivity().getAssets()));

                                name.setTextColor(getResources().getColor(R.color.black));
                                venue.setTextColor(getResources().getColor(R.color.darkgrey));
                                time.setTextColor(getResources().getColor(R.color.black));


                                //ImageView favouriteicon=(ImageView)v.findViewById(R.id.fav_status_image);
            //                  ImageView remindericon=(ImageView)v.findViewById(R.id.reminder_status_image);

                                name.setText(event.getName());
                                time.setText(Html.fromHtml("<b>"+event.getEvent_time()+"</b><br></br>"+event.getEvent_date()));
                                venue.setText(event.getVenue());


                            }
                            return v;
                        }

                    }


                 @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
                        eventnotifierapp app=(eventnotifierapp)getActivity().getApplication();
                        app.crntEvent=(Event) events.get(pos);
                        //startActivity(new Intent(this.getActivity(), EventDescription.class));

                        EventDescriptionFragment frag = EventDescriptionFragment.NewInstance();
                        ((MainActivity)getActivity()).OpenNextFragment(frag);

                    }

            }

ScheduleFragmentAdapter:

    public class ScheduleFragmentAdapter extends FragmentStatePagerAdapter{
        String cat_name;

        protected static final String[] CONTENT = new String[] { "Thursday, Feb 20", 
            "Friday, Feb 21", "Saturday, Feb 22", "Sunday, Feb 23", };

        private int mCount = CONTENT.length;

        public ScheduleFragmentAdapter(FragmentManager fm) {
            super(fm);


        }

        @Override
        public Fragment getItem(int position) {
            if(position == 0)
                return ScheduleListSubFragment.newInstance(day1start, day1end);
            if(position == 1)
                return ScheduleListSubFragment.newInstance(day2start, day2end);
            if(position == 2)
                return ScheduleListSubFragment.newInstance(day3start, day3end);
            else 
                return ScheduleListSubFragment.newInstance(day4start, day4end);
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
          return CONTENT[position % CONTENT.length];
        }
    }

研究 我在stackOverFlow上做了一些挖掘,发现了一些相关的查询,这些查询并不完全相同,但无法找到解决方案

任何帮助,都非常感谢。

1 个答案:

答案 0 :(得分:3)

您好,只需让您的代码运行,有什么帮助我解决您的问题是: 1.在初始化适配器时使用getChildFragmentManager(),如:

fragadapter = new myfragmentAdapter(getChildFragmentManager());

这会给你运行时错误吗? 因为在后退按钮应用程序上没有你的片段上下文(根据我的意见)所以请在后面的堆栈中添加你的片段,如:

public void addpagerfragment(View v)
    {
        pagerFragment frag = pagerFragment.NewInstance();
        crrntfrag = frag;

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.container, frag).addToBackStack(null);
        ft.commit();

    }