Android On Focus Change

时间:2012-05-16 19:57:50

标签: java android

当用户将焦点从edittext更改为另一个项目时,我想更新EditText我想检查edittext的内容,例如,如果大于10,则将其更改为10。

我该怎么做。

4 个答案:

答案 0 :(得分:7)

setOnFocusChangeListener设置为您的edittext ...

editText.setOnFocusChangeListener(new OnFocusChangeListener() {

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

                if(!hasFocus){
              //this if condition is true when edittext lost focus...
              //check here for number is larger than 10 or not
                    editText.setText("10");
                }
            }
        });

答案 1 :(得分:3)

 EditText ET =(EditText)findViewById(R.id.yourtextField);
ET.setOnFocusChangeListener(new OnFocusChangeListener() {
            public void onFocusChange(View arg0, boolean arg1) {

String myText = ET.getText();
//Do whatever

} 

答案 2 :(得分:0)

如果有人想在kotlin中使用数据绑定来进行此操作,请参考以下代码

 //first get reference to your edit text 

 var editText:EditText = viewDataBinding.editText 

 // add listner on edit text 

 editText.setOnFocusChangeListener { v, hasFocus ->
        if(!hasFocus)
        {
      if((editText.text.toString().toIntOrNull()>10)
       {// add any thing in this block
         editText.text = "10"
       }
      }
     }

答案 3 :(得分:0)

如果您有兴趣,请在这篇帖子中进行解释。https://medium.com/@mdayanc/how-to-use-on-focus-change-to-format-edit-text-on-android-studio-bf59edf66161

这是利用OnFocusChangeListener的简单代码

    EditText myEditText = findViewById(R.id.myEditText);

    myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus)
            {
              //Do something when EditText has focus
            }
            else{
              // Do something when Focus is not on the EditText
            }
        }
    });