开发者

onFocusChange code example?

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

Can anyone give me sample code for this?


You have two ways to do this:

  1. 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) {
    
        }
    
    };
    

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜