I created 3 CheckBox containing the colors: red, blue and white. Each checkbox contains a value. The red checkbox contains the value 10. The blue checkbox contains the value 20. And the white checkbox contains the value 30. I would like that when any user clicked on any CheckBox and then pressed the calculateResult button, the textView called showResult would show the sum of the CheckBox values clicked by the user.
My code:
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
CheckBox red;
CheckBox blue;
CheckBox white;
Button calculateResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
red = findViewById(R.id.red);
blue = findViewById(R.id.blue);
white = findViewById(R.id.white);
calculateResult = findViewById(R.id.calculateResult);
final TextView showResult = findViewById(R.id.showResult);
calculateResult.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int result = 0;
if (red.isChecked()) {
result += 10;
}
if (blue.isChecked()) {
result += 20;
}
if (white.isChecked()) {
result += 30;
}
showResult.setText(result);
}
});
}
}```
Aucun commentaire:
Enregistrer un commentaire