本文介绍了节能实例,以避免丢失选项卡之间的数据交换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序有两个标签和标签之间的切换,使我失去了什么,我在输入电流跳闸所以,我修改了code保存状态。

My app has two tabs and switching between the tabs, makes me lose anything I enter in Current Trip So I modified my code to save the state.

package com.test.testing;


public class Trip2 extends Fragment {
     EditText nameOfInf;
    @Override
    public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {

        if ((savedInstanceState != null) && (savedInstanceState.getString("nameof") != null)) {
            Toast.makeText(getActivity(), savedInstanceState.getString("nameof"),2000).show();
        }
        else {
            Toast.makeText(getActivity(), "DIDNT SAVE",2000).show();
        }
        final RelativeLayout mFrame2 =  (RelativeLayout) inflater.inflate( R.layout.trip, container, false );

        final Button btnCalc = (Button) mFrame2.findViewById(R.id.btnCalculate);

        nameOfInf = (EditText) mFrame2.findViewById(R.id.etName);
        final EditText tollAmount = (EditText) mFrame2.findViewById(R.id.etToll);

        btnCalc.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //DO SOMETHING
            }
        });
        return mFrame2;
    }
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("nameof", nameOfInf.toString());
}
}

它始终显示

没救了。

我如何解决这个问题?

推荐答案

您不需要 setRetainInstance ,事实上,不会在所有的工作。

You don't need setRetainInstance, in fact that would not work at all.

什么情况是,pressing标签调用你在哪里,最有可能的,你运行 TabListener A 替换交易,删除旧片段并丢弃其保存的数据。您应该只添加如果标签之前并不存在(使用片段标记来确定)和分离 / 连接其它。一旦你这样做,你甚至不会要救,因为手动视图状态会自动保存在文本。

What happens is that pressing a tab calls your TabListener where, most likely, you run a replace transaction, removing the old fragment and discarding its saved data. You should only add if the tab didn't exist before (use fragment tags to determine that) and detach/attach otherwise. Once you do that, you won't even have to save the text manually since View state is automatically saved.

这篇关于节能实例,以避免丢失选项卡之间的数据交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 07:01