SameerKhan1406 SameerKhan1406 - 18 days ago 9
Android Question

Toggle button checked status on activity startup

Here's my code

public class Abc(){
Public void onCreate(){
Textview ustatus;
ustatus=(Textview)findviewbyid(R.id.status);
statusButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
statusOnline();
// The toggle is enabled
} else {
statusOffline();
// The toggle is disabled
}
}
});
}

public void statusOnline(){
ustatus.setText("Online");
}
public void statusOffline(){
ustatus.setText("Offline");
}
}


I want to know what toggle state would be at the initial on startup suppose in statusOnline and statusOffline method i am doing alot more so i just want that at initial this toggle is intialized with "ON" state.
I don't how to achieve it please bring some light into my code.

Answer
 <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:checked="true"
        android:gravity="bottom"/>

This will create a checkbox that is already ticked. U can change the checked to false if u want an unchecked box. The listner will only call when u interact with the checkbox.

For listener outside onCreate u can do as follows

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //other statements here
        CheckBox checkBox = (CheckBox)findViewById(R.id.checkbox);
        checkBox.setOnCheckedChangeListener(checkedChangeListener);
    }

    CompoundButton.OnCheckedChangeListener checkedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
         //process logic here

        }
    };
Comments