您好我是Java新手并学习如何构建Android应用程序。 我有这个计算器,我一直在努力,我需要帮助找出如何设置EditText的值。当用户在EditText中键入CA,OR或FL时,如何为其分配值? CA = 7%,OR = 8%,FL = 10%,谢谢
public void calculate(View view) {
EditText billET = findViewById(R.id.edit_bill_amount);
EditText tipPercentET = findViewById(R.id.edit_tip_percent);
EditText taxPercentET = findViewById(R.id.edit_tax_percent);
String billString = billET.getText().toString();
String tipPercentString = tipPercentET.getText().toString();
String taxPercentString = taxPercentET.getText().toString();
float bill = Float.parseFloat(billString);
int tipPercent = Integer.parseInt(tipPercentString);
int taxPercent = Integer.parseInt(taxPercentString);
TipCalculator tc = new TipCalculator(tipPercent / 100.0F, bill, taxPercent / 100.0F);
float taxAmount = tc.taxAmount();
float tipAmount = tc.tipAmount();
float total = tc.totalAmount();
TextView taxAmountTV = findViewById(R.id.label_tax_amount_value);
TextView tipAmountTV = findViewById(R.id.label_tip_amount_value);
TextView totalAmountTV = findViewById(R.id.label_total_amount_value);
taxAmountTV.setText(taxAmount + "");
tipAmountTV.setText(tipAmount + "");
totalAmountTV.setText(total + "");
}
答案 0 :(得分:1)
您可以使用 TextWatcher 。
TextWatcher watcher;
watcher=new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) { }
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void afterTextChanged(Editable s) {
edittext.removeTextChangedListener(watcher);
switch(s.toString){
case "CA" :
edittext.setText("7%");
case "OR" :
edittext.setText("8%");
case "FL" :
edittext.setText("10%");
}
edittext.addTextChangedListener(watcher);
}
};
edittext.addTextChangedListener(watcher);
答案 1 :(得分:0)
实施将是这样的
EditText editText = findViewById(R.id.editText);
if (editText.getText().toString().equals("CA")) {
textView.setText("CA=7%");
}
答案 2 :(得分:0)
您可以将这些百分比存储到静态变量中,然后分配它们。如果我正确地解决了您的问题,可能的解决方案如下:
//outside of the calculate method
protected static String CA_PERCENTAGE = "CA = 7%";
protected static String OR_PERCENTAGE = "OR = 8%";
protected static String FL_PERCENTAGE = "FL = 10%";
//inside your calculate method
switch(area){
case "CA" :
tipAmountTV.setText(CA_PERCENTAGE);
case "OR" :
tipAmountTV.setText(OR_PERCENTAGE);
case "FL" :
tipAmountTV.setText(FL_PERCENTAGE);
}
当然这不是“最漂亮”的事情,但是因为你是Java的新手,你可以玩switch statement。