应用程序在尝试输入具有TextChangedListener

时间:2017-10-11 15:11:39

标签: java android crash android-textwatcher

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

我已经为这个程序创建了我的代码但是,每次我尝试在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));
    }
}
}

1 个答案:

答案 0 :(得分:0)

如果要检测文本的更改,可以使用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;
        }
    });

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