使用savedInstanceState更改按钮可见性

时间:2013-08-24 18:26:59

标签: android button visibility

我在这里遇到了一个奇怪的问题。这是我的片段onCreateView:

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

    btnAnswerA = (Button) view.findViewById(R.id.btnAnswerA);
    btnAnswerB = (Button) view.findViewById(R.id.btnAnswerB);
    btnAnswerC = (Button) view.findViewById(R.id.btnAnswerC);
    btnAnswerD = (Button) view.findViewById(R.id.btnAnswerD);

    btnAnswerA.setOnClickListener(this);
    btnAnswerB.setOnClickListener(this);
    btnAnswerC.setOnClickListener(this);
    btnAnswerD.setOnClickListener(this);

    if(savedInstanceState != null) {
        btnAnswerA.setVisibility(savedInstanceState.getInt(ANS_A_ENABLED_KEY));
        btnAnswerB.setVisibility(savedInstanceState.getInt(ANS_B_ENABLED_KEY));
        btnAnswerC.setVisibility(savedInstanceState.getInt(ANS_C_ENABLED_KEY));
        btnAnswerD.setVisibility(savedInstanceState.getInt(ANS_D_ENABLED_KEY));
    }

    return view;
}

和onSaveInstanceState:

@Override
public void onSaveInstanceState(Bundle outState) {

    outState.putInt(ANS_A_ENABLED_KEY, btnAnswerA.getVisibility());
    outState.putInt(ANS_B_ENABLED_KEY, btnAnswerB.getVisibility());
    outState.putInt(ANS_C_ENABLED_KEY, btnAnswerC.getVisibility());
    outState.putInt(ANS_D_ENABLED_KEY, btnAnswerD.getVisibility());

    super.onSaveInstanceState(outState);
}

现在出现了什么问题:在(savedInstanceState!= null)块中,按钮的可见性根本不会改变。即使我手动编写 - btnAnswerA.setVisibility(4) - 它也不会执行。它确实执行了Log命令,我看到savedInstanceState包含所需的值。为什么我这样做:当用户旋转屏幕时,我需要保存按钮的状态。

如果你有任何想法为什么会发生以及如何解决它,我将非常感激!

0 个答案:

没有答案