侦听器检查autocompleteTextview中的第一个字符

时间:2014-09-09 03:30:52

标签: android textview autocompletetextview

我在framelayout中有一个 AutocompleteTextview 和一个删除按钮。我可以输入文字并能够看到我的建议列表和删除按钮以立即清除所有文本。

我想要的是什么:一旦我输入我的第一个字符删除按钮应该可见,当我按下删除按钮时,可见性应该消失。我可以控制按钮的可见性但不知道如何检查第一个输入的字符。请帮我解决这个问题。这就是我在xml中的内容:

<FrameLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    AutoCompleteTextView
        android:id="@+id/srcsutocomplete"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:maxLines="1"
        android:scrollHorizontally="true"
        android:text="My Location "
        android:dropDownSelector="#a0b4f0">

        <requestFocus />
    </AutoCompleteTextView>

    <Button
      android:id="@+id/clearSourceBtn"      
      android:layout_width="30dp"
      android:layout_height="30dp"
      android:layout_marginRight="10dp"
      android:layout_gravity="right|center_vertical"
      android:background="@drawable/ic_navigation_cancel" />

</FrameLayout>

1 个答案:

答案 0 :(得分:1)

要在输入字符后立即显示删除按钮:

使用TextWatcher及其方法。我认为在你的情况下onTextChanged会做到这一点。您可以通过调用YourView.addTextChangedListener(watch)

来添加它
TextWatcher watch = new TextWatcher(){

    public void afterTextChanged(Editable s) {
    /* This method is called to notify you that, 
     somewhere within s, the text has been changed. */
    }

    public void beforeTextChanged(CharSequence s, int count, int start,
      int after) {
    /* This method is called to notify you that, within s, the count 
       characters beginning at start are about to be replaced by new 
       text with length after. */
    }

    public void onTextChanged(CharSequence s, int start, int before, int count) {
    /* This method is called to notify you that, within s, the count characters
       beginning at start have just replaced old text that had length before. */
        if(s.length() > 0) {
            DeleteButton.setVisibility(true);
        }
    }
}};

要使删除按钮在按下后不可见:

DeleteButton.setOnClickListener(new View.OnClickListener({
    void onClick (View v) {
        DeleteButton.setVisibility(false);
    }
};