如何根据EditText的文本隐藏按钮

时间:2018-05-07 20:52:01

标签: android android-studio kotlin android-edittext

如果EditText有文字,我想要按钮可见,否则看不见。

我该如何做到这一点?

我的代码:

class ChargeScreen : AppCompatActivity() {

   override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.cslayout)

        if(editText!==null){
            button.visibility=View.INVISIBLE
        } else {
            button.visibility = View.VISIBLE
        }
        button.setOnClickListener({
                editText.setText("")
                editText.setHint("Type Your Number Of Card")
                button.visibility = GONE
                val inputManager: InputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputManager.hideSoftInputFromWindow(currentFocus.windowToken, InputMethodManager.SHOW_FORCED)
        })
    }
}

1 个答案:

答案 0 :(得分:1)

使用TextWatcher检测EditText内容的更改时间并执行所需操作。

示例(Java):

editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        //called after the EditText's text is changed
        button.visibility = editable.length() > 0 ? View.VISIBLE : View.GONE;
    }
});