我需要在編輯文本的右側顯示一個清除按鈕,並在文本爲「」時將其隱藏。我怎樣才能做到這一點。如何在按下第一個字符後顯示「清除按鈕」,並在文本爲「」時隱藏它?
我只是需要知道如何顯示和隱藏它時,文本長度> 0或= 0,僅此而已。
我需要在編輯文本的右側顯示一個清除按鈕,並在文本爲「」時將其隱藏。我怎樣才能做到這一點。如何在按下第一個字符後顯示「清除按鈕」,並在文本爲「」時隱藏它?
我只是需要知道如何顯示和隱藏它時,文本長度> 0或= 0,僅此而已。
試試這個代碼
Field1.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if(s.length() != 0)
// set the visibility
}
});
@andri:didi u ck this – DKV
設置它的可見性來自xml。
If(editText1.getText.toString.length>0)
{
if(button1.getVisibility == View.GONE)
{
button1.setVisibility(View.VISIBLE)
}
}
else
{
if(button1.getVisibility == View.VISIBLE)
{
button1.setVisibility(View.GONE)
}
}
爲什麼去掉而不是隱藏? –
您可以使用TextWatcher
,類型偵聽器:
yourEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
//Here, you can check for text size...
int length = editText.toString().length();
[...]
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
}
}
從this question服用。
Here是你的答案。
通過檢查字符長度來使用代碼並在textchange上打開和關閉按鈕可見性。
看看下面的代碼,它可以幫助你:
EditText etSearch = (EditText) view.findViewById(R.id.etSearch);
etSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String str = etSearch.getText().toString();
if (str.isEmpty()) {
btnClear.setVisibility(View.INVISIBLE);
} else {
btnClear.setVisibility(View.VISIBLE);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
文本觀察器可以爲你
If(editText1.getText.toString.length>0)
{
if(button1.getVisibility == View.GONE)
{
button1.setVisibility(View.VISIBLE)
}
}
else
{
if(button1.getVisibility == View.VISIBLE)
{
button1.setVisibility(View.GONE)
}
}
使用TextWatcher – DKV
可能的重複工作[計數中的EditText個字符改變監聽器] (http://stackoverflow.com/questions/4310525/counting-chars-in-edittext-changed-listener) –
看看這個http://www.devexchanges.info/2015/04/android-edittext-with -cross-button-in.html –