【发布时间】:2016-01-18 15:25:47
【问题描述】:
我在应用程序中有一个EditBox 和一个TextView。
我希望 TextView 在我输入时将我在 EditBox 中输入的数字转换为单词(onTextChanged())并显示出来。
我制作了将数字转换为单词的类,它可以正常工作。
我搜索onTextChanged事件,我找到了如何使用它,但我遇到了一个问题。
代码如下:
ed.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
String num = ed.getText().toString();
String str = num.replace(",", "");
double x = Double.parseDouble(str);
String text = NumberFormat.getIntegerInstance(Locale.US).format(x);
ed.setText(text);
/*if (ed.length() != 0)
{
String numtoalph = NumToAlph.convert(x);
tv.setText( numtoalph + tv.getText().toString());
}*/
NumToAlph numToAlph = new NumToAlph();
String alph = NumToAlph.Convert(text, x);
tv.setText(alph + " ریال");
}
catch (Exception ex)
{
tv.setText(ex.toString());
}
@Override
public void afterTextChanged(Editable s) {}
});
*NumToAlph 是类
当我将它安装在手机上并尝试在按下第一个按钮时输入时,应用程序冻结了,一分钟后我收到一条通知,上面写着
此应用占用过多 CPU
我测试了代码,我的意思是这个
try {
String num = ed.getText().toString();
String str = num.replace(",", "");
double x = Double.parseDouble(str);
String text = NumberFormat.getIntegerInstance(Locale.US).format(x);
ed.setText(text);
/*
if (ed.length() != 0)
{
String numtoalph = NumToAlph.convert(x);
tv.setText( numtoalph + tv.getText().toString());
}
*/
NumToAlph numToAlph = new NumToAlph();
String alph = NumToAlph.Convert(text, x);
tv.setText(alph + " ریال");
}
catch (Exception ex)
{
tv.setText(ex.toString());
}
在按钮单击事件中,它工作得又快又正确。 有人知道这个问题吗?
我之前用 C# 为 windows 编写过这个应用程序,并将它用于 textChanged 事件没有问题:
decimal Number;
if (decimal.TryParse(textBox1.Text, out Number))
{
textBox1.Text = string.Format("{0:N0}", Number);
textBox1.SelectionStart = textBox1.Text.Length;
}
try
{
NumToAlph dd = new NumToAlph();
string x = textBox1.Text.Replace(",", "").ToString();
textBox2.Text = dd.num2str(x) + " ریال";
}
catch (Exception ex)
{
MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
【问题讨论】:
标签: android cpu textwatcher textchanged