Checkbox checked/unchecked does not obey instructions

Asked

Viewed 348 times

2

To Activity is started with the layout activity_home and the CheckBox unchecked. When I touch CheckBox, the layout becomes the activity_home_avancado, however the Checkbox remains unmarked. At the second touch, she is marked and the layout remains as the advanced. On the third touch, the CheckBox is unmarked, but layout active remains being the activity_home_avancado. Why these two mistakes?

Follows the code:

public class HomeActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    final CheckBox checkBoxAvancado = (CheckBox) findViewById(R.id.modoavancado_cb);

    checkBoxAvancado.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (checkBoxAvancado.isChecked()) {
                setContentView(R.layout.activity_home_avancado);
            }
            else {
                setContentView(R.layout.activity_home);
            }
        }
    });


    } //fecha onCreate
}

And the same CheckBox present in the two archives XML:

<CheckBox
            android:id="@+id/modoavancado_cb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:textColor="#7F7F7F"
            android:text="@string/modoavancado" />

(nothing appears in Logcat)

1 answer

3

Although, in each of the Layouts, as Checkbox’s have the same id they are not the same object.

When the method is used (CheckBox) findViewById(R.id.modoavancado_cb), this will look for the modoavancado_cb in the Layout which has been associated with Activity, through setContentView()

When the Listener, to the Checkedchanged, this is associated with Checkbox of Layout R.layout.activity_home because that’s the Layout which is currently associated with Activity

What’s happening is that the code of onCheckedChanged() is executed only once.
When the other is assigned Layout à Activity in

if (checkBoxAvancado.isChecked()) {
    setContentView(R.layout.activity_home_avancado);
}

the Checkbox that appears now on the screen is the one defined in the XML of Layout activity_home_advanced and not that of activity_home.

Like this Checkbox has no OnCheckedChangeListener associate, nothing happens when it is marked.

The setContentView should only be used once.
To change the contents of the screen create another Activity, utilize Fragments or Hide/show Views of Layout

Browser other questions tagged

You are not signed in. Login or sign up in order to post.