Android onFocusChange 代码示例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2841973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
onFocusChange code example?
提问by Rich
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
我有一个包含 2 个字段的表单,您可以在其中输入数月或数年。我如何设置表单,以便如果您输入年份,则将自动计算月份编辑文本字段并将其输入到它自己的框中。同样,如果您输入月份,我希望计算年份
Can anyone give me sample code for this?
任何人都可以给我示例代码吗?
回答by Ravi Vyas
You have two ways to do this:
您有两种方法可以做到这一点:
Do character by character processing of one field to calculate the other field
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) { } };
对一个字段进行逐字处理以计算另一字段
为此,您可以将 addTextChangedListener 与文本观察器一起使用,您可以在其中更改 onTextChanged 方法来处理数据。
//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 . The other method is to calculate the data when the user changes focus to the other field.
2 . 另一种方法是计算用户将焦点转移到其他字段时的数据。
Here you need to use the onFocusChangeListener:
这里需要使用 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.
无论哪种方式,根据您可能想要检查有效输入的设计。