Android 保存和恢复片段状态?

Android 保存和恢复片段状态?,android,android-fragments,Android,Android Fragments,我正在使用Fragment,在此Fragment中,我使用fromonSaveInstanceState在配置更改时保存和恢复片段状态 但是当我得到Log时,给我所有的颜色51: Log.i("LOG", r + " " + g + " " + b); 下面是我的代码: public class SecondFragment extends Fragment implements View.OnClickListener { private Button secondFragmen

我正在使用
Fragment
,在此
Fragment
中,我使用from
onSaveInstanceState
在配置更改时保存和恢复
片段状态

但是当我得到
Log
时,给我所有的
颜色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);
    }
}

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

此外,将这些键设置为静态最终键也是一种很好的做法