零基础学android,跟着官方教程学完第三课,点饮料这个程序,根据自己的构想,想试试用现有的知识点做点改变。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void displayMessage(String message) {
TextView wenBenTextView = (TextView) findViewById(R.id.wenBen_view);
wenBenTextView.setText(message);
}
public void Sure(View view) {
RadioButton milkTeaRadio = findViewById(R.id.radio_milkTea);
boolean hasMilkTea = milkTeaRadio.isChecked();
RadioButton colaRadio = findViewById(R.id.radio_cola);
boolean hasCola = colaRadio.isChecked();
CheckBox iceCheckBox = findViewById(R.id.ice_CheckBox);
boolean hasIce = iceCheckBox.isChecked();
CheckBox bubbleCheckBox = findViewById(R.id.bubble_CheckBox);
boolean hasBubble = bubbleCheckBox.isChecked();
String milkTea = "";
if (hasMilkTea) {
milkTea = "奶茶";
}
String cola = "";
if (hasCola) {
cola = "可乐";
}
String ice = "";
if (hasIce) {
ice = "+冰块";
}
String bubble = "";
if (hasBubble) {
bubble = "+珍珠";
}
String priceMessage = createOrderSummary(milkTea, cola, ice, bubble);
displayMessage(priceMessage);
}
private String createOrderSummary(String milk, String cola, String ice, String bubble) {
String priceMessage = milk;
priceMessage += cola + ice + bubble;
return priceMessage;
}
}
点奶茶或可乐,+配料都能正常显示出文本,相当于小票信息。
我现在想点击确认1次,文本显示所定饮料的信息;点击确认第二次,文本自动换行+所点饮料信息。
例如:奶茶+冰+珍珠
可乐+冰
奶茶+珍珠。
问题②,单选按钮,我尝试用以下代码代替上面的2个单选代码,这样会简洁很多,但是chedced
的true,怎么分辨是奶茶还是可乐的,文本的信息该怎么写。
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.radio_milkTea:
if (checked)
break;
case R.id.radio_cola:
if (checked)
break;
}
}