Harold Giddings Harold Giddings - 6 months ago 7
Java Question

Have Button Check the State of CheckBoxes

I would like to get my button (bConnect) to check the state of my licensed and authorized checkbox.

Allowing me to use an If / Else statement to open a new activity if the boxes are indeed checked, otherwise open an alert dialog and tell the user they are not authorized unless those checkboxes are checked.

public class ConnectAPRS extends AppCompatActivity {

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

final EditText callsign = (EditText) findViewById(R.id.callsign);
final EditText passcode = (EditText) findViewById(R.id.passcode);
final CheckBox licensed = (CheckBox) findViewById(R.id.licensed);
final CheckBox authorized = (CheckBox) findViewById(R.id.authorized);

final Button bConnect = (Button) findViewById(R.id.bConnect);

bConnect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(ConnectAPRS.this, Contacts.class));
}
});
}
}

Answer
public class ConnectAPRS extends AppCompatActivity {

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

        final EditText  callsign = (EditText)   findViewById(R.id.callsign);
        final EditText  passcode = (EditText)   findViewById(R.id.passcode);
        final CheckBox  licensed = (CheckBox)   findViewById(R.id.licensed);

        final Button    bConnect = (Button)     findViewById(R.id.bConnect);

        bConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (licensed.isChecked())
                    startActivity(new Intent(ConnectAPRS.this, Contacts.class));
                else
                    new AlertDialog.Builder(ConnectAPRS.this)
                            .setTitle("ERROR")
                            .setMessage("You are not a licensed operator")
                            .show();
            }
        });
    }
}
Comments