onFocusChange code的例子吗?例子、onFocusChange、code

2023-09-06 02:41:11 作者:旺仔味的老干妈

我有2个字段,您可以在任何几个月或几年进入一个形式。如何设置,这样,如果你在未来几年进入,几个月的EditText字段将自动计算并输入到它自己的盒子的形式。同样,我想如果你在未来几个月进入年来计算的。

I have a form with 2 fields where you can enter in either months or years. How do I setup the form so that if you enter in the years, the months edittext field will be automatically calculated and entered into it's own box. Likewise, I want the years to be calculated if you entered in the months

谁能给我的样品code这个?

Can anyone give me sample code for this?

推荐答案

您有两种方法可以做到这一点:

You have two ways to do this:

按字符的处理做一域字符计算其他领域

Do character by character processing of one field to calculate the other field

有关这一点,你可以使用addTextChangedListener与在那里你改变onTextChanged方法来处理数据的文本观察者。

For this you may use the addTextChangedListener with a text watcher where you change the onTextChanged method to process the data.

//from editHandle = (EditText) findViewById(R.id. <<your EditText>> );

editHandle.addTextChangedListener(redoWatcher);

// listener
private TextWatcher redoWatcher = new TextWatcher() {


    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
    }

    @Override   
    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        recalculate();
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

};

现在,你可以写重新计算方法来处理数据。

Now you can write the recalculate method to process the data.

2。另一种方法是计算数据,当用户更改聚焦到其它领域。

2 . The other method is to calculate the data when the user changes focus to the other field.

在这里,你需要使用onFocusChangeListener:

Here you need to use the onFocusChangeListener:

<Your EditView>.setOnFocusChangeListener(new OnFocusChangeListener() {

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        recalculate();
    }
});

无论哪种方式,取决于设计,你可能要检查的有效输入。

Either way, depending on the design you might want to check for valid input.