繁体   English   中英

保存和恢复片段状态?

[英]Saving and Restoring Fragment State?

我正在使用Fragment ,在此Fragment ,当配置更改时,我使用onSaveInstanceState来保存和还原Fragment State

但是当我得到Log让我获得所有colors 51

Log.i("LOG", r + "  " + g + "  " + b);

下面是我的代码:

public class SecondFragment extends Fragment implements View.OnClickListener
{
    private Button secondFragmentButton;
    String MY_Red;
    String MY_Green;
    String MY_Blue;
    public SecondFragment()
    {
        super();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.fragment_second, container, false);

        secondFragmentButton = (Button) rootView.findViewById(R.id.fragment_second_button);
        secondFragmentButton.setOnClickListener(this);

        if (savedInstanceState != null) {
            int r = savedInstanceState.getInt(MY_Red);
            int g = savedInstanceState.getInt(MY_Green);
            int b = savedInstanceState.getInt(MY_Blue);
            Log.i("LOG", r + "  " + g + "  " + b);
            secondFragmentButton.setBackgroundColor(Color.rgb(r, g, b));
        }
        return rootView;
    }

    @Override
    public void onClick(View v)
    {
        if(v == secondFragmentButton)
        {
            Toast.makeText(getActivity(), getActivity().getString(R.string.example_text), Toast.LENGTH_LONG).show();
            secondFragmentButton.setBackgroundColor(Color.rgb(255, 153, 51));
        }
    };

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(MY_Red, 255);
        outState.putInt(MY_Green, 153);
        outState.putInt(MY_Blue, 51);
    }
}

您是否尝试过将键Strings声明/初始化为不同的值? My_RedMy_GreenMy_Blue具有相同的( null )值,因为它们My_Blue初始化。 因此,每次调用putInt ,都会覆盖该捆绑包,从而导致在onSaveInstanceState之后的捆绑包中只有一对键值对( null : 51 )。 当在onCreateView中调用getInt ,实际上您将执行三次相同的功能(使用相同的键),这将导致rgb具有相同的值。

同样,将这些键设置为static final是一个好习惯。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM