开发者

Handle orientation from Portrait to Landscape mode for Checkbox

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);
}

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.


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) 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).

saving state:

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

recovering it in onCreate:

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

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.


Write this in your manifest file..in which activity you want this--

<activity android:name=".TestActivity" android:configChanges="orientation|keyboardHidden"/>

Definitely it will works..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜