dimanche 18 novembre 2018

Android Checkbox

I have added 3 checkboxes dynamically, the problem is, when I check checkboxes 1 and 2, it raises "No CheckBox Checked" toast, but when I check checkbox 3, it raises "Checkbox 3 is checked" toast. So how do I make the checkboxes 1 and 2 bring up the same toast when I check checkbox 3 ?

This is the full code of the MainActivity:

public class MainActivity extends Activity {

EditText text;
TextView tx, jText;
CheckBox noCheck, jCheck;
LinearLayout l1;
int checkId = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    text = (EditText)findViewById(R.id.edit);
    l1 = (LinearLayout)findViewById(R.id.CheckBoxLayout);
    noCheck = (CheckBox)findViewById(R.id.noCheck);

}

public void fTambah(View view) {

    /**
     * Tambah.onClick function
     * To add checkbox dynamically
     * @param textData - EditText text data
     * @param jCheck - New CheckBox
     * @param jText - New TextView baru
     */

    checkId++;
    String textData = text.getText().toString();
    jCheck = new CheckBox(this);
    jText = new TextView(this);

    if (noCheck.isChecked()) {
        jText.setText(textData);
        l1.addView(jText);
    } else {
        jCheck.setTag(checkId);
        jCheck.setText(textData);
        jCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (jCheck.isChecked()) {
                    Toast.makeText(MainActivity.this, "CheckBox " + jCheck.getTag().toString() + " is checked", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(MainActivity.this, "No Checkbox Checked", Toast.LENGTH_LONG).show();
                }
            }
        });

        // Add CheckBox to layout
        l1.addView(jCheck);

    }   
}

}




Aucun commentaire:

Enregistrer un commentaire