我正在开发一个人们将输入账单的Android应用程序。 我有一个EditText,人们输入金额。
我想要做的是例如如果一个人输入“2”,它应该自动转换为“0.02”。然后,如果他/她想要输入22 $,他应该按下2个,2个,0个和0个按钮。它就像“22.00”。如何使用EditText设法完成此操作。你能给我一些想法吗?
以下是相关代码:
<EditText
android:id="@+id/amount"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dip"
android:layout_marginTop="5dip"
android:inputType="number"
android:hint="@string/enter_amount"
android:singleLine="true" />
EditText payment = (EditText) findViewById(R.id.amount);
if (payment.getText().toString().length() > 0){
total_amount =Integer.parseInt(payment.getText().toString()) ;
}
答案 0 :(得分:3)
EditText payment = (EditText) findViewById(R.id.amount);
payment.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
total_amount =Integer.parseInt(s) ;
payment.setText(""+(total_amount/100));
}
});
答案 1 :(得分:2)
为此你必须像这样使用textWatcher:
payment.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
答案 2 :(得分:1)
使用addTextChangedListener()
edittext.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
答案 3 :(得分:0)
EditText payment = (EditText) findViewById(R.id.amount);
if (payment.getText().toString().length() > 0){
double total_amount =Double.parseDouble(payment.getText().toString()) ;
String amm = String.valueOf(total_amount/100);
payment.setText(amm);
答案 4 :(得分:0)
您正在寻找TextWatcher
以便在输入时更改输入。这是一个例子:
TextWatcher paymentWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
//Do your calculations here
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
};
payment.addTextChangedListener(paymentWatcher);