【问题标题】:FragmentPagerAdapter not restoring fragments upon Orientation ChangeFragmentPagerAdapter 在方向更改时不恢复片段
【发布时间】:2013-08-27 20:26:42
【问题描述】:

编辑:我发现 Activity 正在保存实例,但 Fragments 保存的数据并没有弥补 Activity savedInstanceState。我将当前时间保存在 outState 中,但它并没有一路上升,因为活动在其 SavedInstanceState 中没有任何时间,如果我将其打印到 logcat 则返回“null”。 ..

我正在构建一个内置倒计时和倒计时计时器的应用程序。计时器的基本托管活动是一个 FragmentActivity,它托管一个 FragmentPagerAdapter,它在代码中膨胀两个片段(我不给片段一个 id在 XML 中,因为它们未定义为 .xml 中的片段)。一切都很好,直到方向发生变化,然后活动看起来就像它失去了与旧片段的联系,只是选择创建新片段。这意味着任何当前的倒计时都会丢失,并且任何选择的时间也会在配置更改时丢失。我需要继续计数(如果它开始了)和当前显示的任何数字....

我知道适配器应该自己处理这些事情,我在 OnCreate 和 OnCreateView 中都设置了 SetRetainInstance(true)。

我在 Fragment 代码中添加了钩子,以便让我知道 saveInstanceState 何时不为空,所以至少我知道发生了什么,但似乎该实例始终为 NULL,并且它从头开始创建......总是.

其他一些解决方案让我覆盖了 instantiateItem,但它似乎仅用于重置回调,其他解决方案更改 Manifest 中的设置(皱眉)......其他解决方案在我看来就像我已经设置了东西对......但很明显,我在路上搞砸了一些事情。我只提供 FragmentActivity、FragementPagerAdapter 的代码和一些 Fragment 代码,因为我不想用可能不是问题的代码向帖子发送垃圾邮件。

片段活动

public class Timer_Main extends FragmentActivity {
    ViewPager pager;
    Timer_Pager mAdapter;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.timer_pager);

        mAdapter = new Timer_Pager(this, getSupportFragmentManager());

        pager = (ViewPager) findViewById(R.id.timer_pager_display);
        pager.setAdapter(mAdapter);

    }

    public static String getTitle(Context ctxt, int position) {
                // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("pageItem", pager.getCurrentItem());

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

    }
}    

FragmentPagerAdapter

public class Timer_Pager extends FragmentPagerAdapter{
    Context ctxt = null;
    public Timer_Pager(Context ctxt, FragmentManager fm) {
        super(fm);
        this.ctxt = ctxt;
        }


    @Override
    public Fragment getItem(int position) {

        switch (position) {
        case 0: {
            return(Countdown_Fragment.newInstance());
        }
        case 1:
            return(Countup_Fragment.newInstance());
        }
        return null;
    }

    @Override
    public String getPageTitle(int position) {

        switch (position) {
        case 0: 
            return(String.format(ctxt.getString(R.string.Countdown_label)));
        case 1: 
            return(String.format(ctxt.getString(R.string.Countup_label)));
        }
        return null;
    }

    @Override
    public int getCount() {
        // doing only three pages, right now...one for countdown, one for countup,         and one for Tabata.
        return 2;
    }

    private static String makeFragmentName(int viewId, int position)
    {
         return "android:switcher:" + viewId + ":" + position;
    }
}    

Fragment 里面有更多代码,所以我将推送应该是问题核心的内容....如果需要更多,我会拼接它。

public class Countdown_Fragment extends Fragment implements OnClickListener {
    Calendar CountdownTime = Calendar.getInstance();
    static AutoResizeTextView tv;
    static ImageButton HoursUp;
    static ImageButton HoursDown;
    static ImageButton MinutesUp;
    static ImageButton MinutesDown;
    static ImageButton SecondsUp;
    static ImageButton SecondsDown;
    static ImageButton Reset;
    static ImageButton StartPausecount;
    static ImageButton Stopcount;
    static Boolean Arewecounting = false;
    static Boolean Arewecountingdown = false;
    static AutoResizeTextView ThreetwooneGO;
    static MyCountdownTimer Countdown_Timer_Activity;
    ThreetwooneCount Start_countdown;
    static Long MillstoPass;

    static Countdown_Fragment newInstance() {

        Countdown_Fragment frag = new Countdown_Fragment();
        return (frag);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {

        outState.putString("CurrentTimer", (String) tv.getText());
        Log.v("status", "saved fragment state" + tv.getText());
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

    }

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

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

            setRetainInstance(true);
            View result = inflater.inflate(R.layout.countdown_timer_layout,
                container, false);
        tv = (AutoResizeTextView) result.findViewById(R.id.timer_textview);
        tv.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                new TimePickerDialog(getActivity(), t, 0, 0, true).show();
            }
        });
        if (savedInstanceState != null) {
            Log.v("status", "fragment is NOT empty");
            tv.setText(savedInstanceState.getString("CurrentTimer",
                    tv.toString()));
        } else {
            Log.v("status", "fragment is empty");
        //  tv.setText("00:00:00");

        }
        tv.resizeText();

        ThreetwooneGO = (AutoResizeTextView) result
                .findViewById(R.id.timer_countdown_text);

        HoursUp = (ImageButton) result.findViewById(R.id.hours_up);
        HoursDown = (ImageButton) result.findViewById(R.id.hours_down);
        MinutesUp = (ImageButton) result.findViewById(R.id.minutes_up);
        MinutesDown = (ImageButton) result.findViewById(R.id.minutes_down);
        SecondsUp = (ImageButton) result.findViewById(R.id.seconds_up);
        SecondsDown = (ImageButton) result.findViewById(R.id.seconds_down);
        Reset = (ImageButton) result.findViewById(R.id.reset);
        StartPausecount = (ImageButton) result
                .findViewById(R.id.startpausecount);
        Stopcount = (ImageButton) result.findViewById(R.id.stopcount);

        HoursUp.setOnClickListener(this);
        HoursDown.setOnClickListener(this);
        SecondsUp.setOnClickListener(this);
        SecondsDown.setOnClickListener(this);
        MinutesUp.setOnClickListener(this);
        MinutesDown.setOnClickListener(this);
        Reset.setOnClickListener(this);
        StartPausecount.setOnClickListener(this);
        Stopcount.setOnClickListener(this);

        return (result);
    }

    public void chooseTime(View v) {
        new TimePickerDialog(getActivity(), t, 0, 0, true).show();
    }

    TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            CountdownTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
            CountdownTime.set(Calendar.MINUTE, minute);
            CountdownTime.set(Calendar.SECOND, 0);
            CountdownTime.set(Calendar.MILLISECOND, 0);

            updateLabel();
        }
    };

    private void updateLabel() {

        String entiretime;
        entiretime = String.format("%tT", CountdownTime);
        tv.setText(entiretime);
    }

这是我用于倒计时的计时器......

public class MyCountdownTimer {

private long millisInFuture;
private long countDownInterval;
Countdown_Fragment ctxt;
AutoResizeTextView Timer_edit;
private volatile boolean IsStopped = false;

public MyCountdownTimer(long pMillisInFuture, long pCountDownInterval,
        AutoResizeTextView Artv) {
    this.millisInFuture = pMillisInFuture;
    this.countDownInterval = pCountDownInterval;

    Timer_edit = Artv;

}

public void Start() {

    final Handler handler = new Handler();
    final Runnable counter = new Runnable() {

        public void run() {
            if (IsStopped == false) {
                if (millisInFuture <= 0) {
                    Countdown_Fragment.done_counting();
                } else {
                    long sec = millisInFuture / 1000;
                    Timer_edit.setText(String.format("%02d:%02d:%02d",
                            sec / 3600, (sec % 3600) / 60, (sec % 60)));
                    millisInFuture -= countDownInterval;
                    handler.postDelayed(this, countDownInterval);
                }
            }
        }
    };

    handler.postDelayed(counter, countDownInterval);
}

public void Cancel() {
    IsStopped = true;
    Timer_edit = null;
    Log.v("status", "Main Timer cancelled");
    // this.ctxt = null;

}
public long whatisourcount(){
    return(millisInFuture);
}
}

【问题讨论】:

    标签: android android-fragments android-fragmentactivity android-pageradapter


    【解决方案1】:

    事实证明,RetainInstance 引起了自身与 ViewPager/Adapter/FragmentManager 之间的冲突。删除它会导致寻呼机正确重建 Fragment,包括我拥有的 TextView,而以前没有。我也开始在 OnCreateView 中收到一个 Bundle,之前它总是为 null,而 RetainInstance 设置为 True。

    我不得不移除 RetainInstance 并利用 OnSaveInstanceState 和 OnCreateView 传入 Fragment 在销毁之前的当前状态,然后在 OnCreateView 中重新创建它以将 Fragment 重置为销毁之前的状态。

    我希望我用来倒计时的 Runnable 能够幸存下来,或者我能够重新连接它,但我找不到方法。我必须以毫秒为单位保存当前计数,然后传回 Fragment 以从中断处继续。这没什么大不了的,但我很想知道你是否可以真正重新连接所有这些东西。配置更改后,Runnable 仍然继续,但它不再更新 UI 上的任何内容,所以我尝试取消回调并将其设为 null,当我在 OnSaveInstanceState 中时。

    我也在阅读那些我只需要对附加了 AsyncTask 的项目或其他类似项目使用 RetainInstance 的项目......否则,只需在代码中重建它。

    【讨论】:

    • 嗨..我面临着类似的问题。有没有办法保持设置保留实例为真并使其工作,否则我应该重写我的整个逻辑。在此先感谢:)
    • 找不到解决办法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 2021-12-23
    • 2014-03-17
    • 2015-06-09
    • 1970-01-01
    相关资源
    最近更新 更多