繁体   English   中英

尝试在具有 TextChangedListener 的编辑文本上输入时应用程序崩溃

[英]Application Crashed when trying to input on an edittext that has an TextChangedListener

我试图创建一个自动计算百分比的应用程序。 百分比值将显示在 TextView 中。 将在 textview 中显示的值将基于用户在 edittext 中输入的值。

我已经为这个程序创建了我的代码,但是每次我尝试在编辑文本中输入一些数字时它都会崩溃。

我希望你明白我在说什么。 这是我的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sample__table);
    btnAdd = (Button)findViewById(R.id.btnAdd);
    //btn Function
    btnAdd.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
         AddRow();
        }
    });
    //end of btn function

    //text changed
    tl = (TableLayout) findViewById(R.id.tl);
    row = new TableRow(this);
    TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
    row.setLayoutParams(lp);
    fruit = new EditText(this);
    freq = new EditText(this);
    perc = new TextView(this);
    freq.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
            ReCalculate();
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        public void onTextChanged(CharSequence s, int start, int before, int count) {}
    });
    //text changed end
}
private void AddRow(){

    row.addView(fruit);
    row.addView(freq);
    row.addView(perc);
    tl.addView(row);
}
private void ReCalculate(){
    float sum = 0f;
    int rows = tl.getChildCount();
    // Get the total
    for (int i = 0; i < rows; i++) {
        TableRow elem = (TableRow) tl.getChildAt(i);
        sum+= Integer.parseInt(((EditText)elem.getChildAt(1)).getText().toString());
    }
    // Recalculate every row percent
    for (int i = 0; i < rows; i++) {
        TableRow elem = (TableRow) tl.getChildAt(i);
        int amount​ = Integer.parseInt(((TextView)elem.getChildAt(1)).getText().toString());
        ((TextView)elem.getChildAt(1)).setText(String.valueOf(amount​/sum*100));
    }
}
}

如果要检测文本的更改,可以使用 onKeyListener:

    EditText edtText = (EditText)findViewById(R.id.editText);
    edtText.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View view, int i, KeyEvent keyEvent) {
            Toast.makeText(MainActivity.this, "Text changed!", Toast.LENGTH_SHORT).show();
            return false;
        }
    });

它对我有用,希望它有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM