处理从纵向方向为横向模式复选框纵向、横向、复选框、方向

2023-09-13 02:13:47 作者:爱你不如爱狗

我使用的布局XML的复选框。

I am using the Checkbox on a layout xml .

<CheckBox android:id="@+id/chkbox" 
android:checked="false" android:button="@drawable/ic_uncheck_img">

该复选框被默认设置为假&放大器;一个图像增加了对未选中按钮。

The Checkbox is by default set to "false" & a image is added for unchecked button.

private CheckBox mCheck= null;

public void onCreate(Bundle savedInstanceState) {

mCheck= (CheckBox) findViewById(R.id.chkbox);
        mCheck.setChecked(false);
        mCheck.setButtonDrawable(R.drawable.ic_uncheck_img);


}

public void onClick(View view) {

            if (view.getId() == R.id.chkbox) {
                if (mCheck.isChecked())
                    mCheck.setButtonDrawable(R.drawable.ic_check_img);
                else
                    mCheck.setButtonDrawable(R.drawable.ic_uncheck_img);
}

在onClick的(),当用户点击复选框,从取消选中图像的变化来检查。用户确实是在肖像模式。

Within the onClick() , when the user clicks on the Checkbox , the image changes from uncheck to check . User does that on the portrait mode.

当用户改变方向到所述装置的横向模式,所述校验消失&安培;在取消选中图像显示。当方向从纵向改为横向复选框的状态不会维持。

When the user changes orientation to the landscape mode of the device, the check disappears & the uncheck image is displayed . The state of the Checkbox is not maintained when the orientation changes from portrait to landscape.

请提供您的投入就如何保持复选框的状态,即使方向改变。

Kindly provide your inputs on how to maintain the state of the Checkbox even if the orientation changes.

在此先感谢。

亲切问候,

CB

推荐答案

这是发生,因为默认情况下,在方向的变化引起的活动重新启动(即你的当前实例被破坏,该活动的新实例使用的onCreate创建())。

This is happening because, by default, a change in orientation causes the activity to restart (ie. your current instance is destroyed, and a new instance of the activity is created using onCreate() ).

有一对夫妇的方式我能想到的来完成你所需要的。

There are a couple ways I can think of to accomplish what you need.

1)保存使用的onSaveInstanceState束的复选框的状态,并在您的onCreate恢复它()。 (记住要处理这两种情况:启动该活动的第一次,当savedInstanceState包不会在那里)。

1) Save the the state of the checkbox using the onSaveInstanceState bundle, and recover it in your onCreate(). (Remember to handle both cases: the savedInstanceState bundle will not be there when starting the activity the first time).

节能状态:

@Override 
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putBoolean("CHECKBOX_STATE", mCheckbox.isChecked());
    super.onSaveInstanceState(savedInstanceState);
}

恢复它的onCreate:

recovering it in onCreate:

if(savedInstanceState != null) {
    mCheckBox.setChecked(savedInstanceState.getBoolean("CHECKBOX_STATE"));
}

2)在AndroidManifest,设置属性机器人:configChanges =方向,在有关活动。这将导致当方向改变它无法重新启动。

2) In the AndroidManifest, set the attribute "android:configChanges="orientation"" in the activity in question. This will cause it to not restart when orientation is changed.