保存和恢复碎片状态?

时间:2015-03-18 15:48:24

标签: android android-fragments

我正在使用FragmentFragment我在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);
    }
}

以下是我的代码:

{{1}}

1 个答案:

答案 0 :(得分:0)

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

此外,制作这些密钥static final是一种很好的做法。