【问题标题】:how can I create clean Button in AutoCompleteTextView如何在 AutoCompleteTextView 中创建干净的按钮
【发布时间】:2015-07-26 11:47:11
【问题描述】:

如何在 AutoCompleteTextView 中创建干净的按钮,当我单击清除按钮时,我想清除 AutoCompleteTextView 中的所有文本,见图

【问题讨论】:

    标签: android


    【解决方案1】:

    正如 Michael Derazon 在this post 中所解释的,您可以扩展 AutoCompleteTextView 以包含自定义清除功能。实现将如下所示:

    import android.content.Context;
    import android.graphics.drawable.Drawable;
    import android.util.AttributeSet;
    import android.view.MotionEvent;
    import android.view.View;
    import android.widget.AutoCompleteTextView;
    
    /**
     * sub class of {@link android.widget.AutoCompleteTextView} that includes a clear (dismiss / close) button with
     * a OnClearListener to handle the event of clicking the button
     * based on code from {@link http://www.gubed.net/clearableautocompletetextview}
     * @author Michael Derazon
     *
     */
    public class ClearableAutoCompleteTextView extends AutoCompleteTextView {
        // was the text just cleared?
        boolean justCleared = false;
    
        // if not set otherwise, the default clear listener clears the text in the
        // text view
        private OnClearListener defaultClearListener = new OnClearListener() {
    
            @Override
            public void onClear() {
                ClearableAutoCompleteTextView et = ClearableAutoCompleteTextView.this;
                et.setText("");
            }
        };
    
        private OnClearListener onClearListener = defaultClearListener;
    
        // The image we defined for the clear button
        public Drawable imgClearButton = getResources().getDrawable(
                R.drawable.abc_ic_clear_holo_light);
    
        public interface OnClearListener {
            void onClear();
        }
    
        /* Required methods, not used in this implementation */
        public ClearableAutoCompleteTextView(Context context) {
            super(context);
            init();
        }
    
        /* Required methods, not used in this implementation */
        public ClearableAutoCompleteTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();
        }
    
        /* Required methods, not used in this implementation */
        public ClearableAutoCompleteTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }
    
        void init() {
            // Set the bounds of the button
            this.setCompoundDrawablesWithIntrinsicBounds(null, null,
                    imgClearButton, null);
    
            // if the clear button is pressed, fire up the handler. Otherwise do nothing
            this.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
    
                    ClearableAutoCompleteTextView et = ClearableAutoCompleteTextView.this;
    
                    if (et.getCompoundDrawables()[2] == null)
                        return false;
    
                    if (event.getAction() != MotionEvent.ACTION_UP)
                        return false;
    
                    if (event.getX() > et.getWidth() - et.getPaddingRight() - imgClearButton.getIntrinsicWidth()) {
                        onClearListener.onClear();
                        justCleared = true;
                    }
                    return false;
                }
            });
        }
    
        public void setImgClearButton(Drawable imgClearButton) {
            this.imgClearButton = imgClearButton;
        }
    
        public void setOnClearListener(final OnClearListener clearListener) {
            this.onClearListener = clearListener;
        }
    
        public void hideClearButton() {
            this.setCompoundDrawables(null, null, null, null);
        }
    
        public void showClearButton() {
            this.setCompoundDrawablesWithIntrinsicBounds(null, null, imgClearButton, null);
        }
    
    }
    

    有关如何实现它的完整指南,请参阅full post。结果如下图:

    【讨论】:

    • 嗨,我已经创建了一个这样的类,但是当调用 class ClearableAutoCompleteTextView searchBox = (ClearableAutoCompleteTextView)root.findViewById(R.id.autoCompleteTextViewFrom);我接受这个错误; java.lang.ClassCastException:android.widget.AutoCompleteTextView 无法转换为 com.android.app.ClearableAutoCompleteTextView
    • 你也想改变你的xml @android java
    • R.id.autoCompleteTextViewFrom 必须是 ClearableAutoCompleteTextView。 @androidjava
    • Ja, jag har bytt den men jag har samma 问题
    • Taggen i xml måste vara @androidjava
    【解决方案2】:

    试试这个:

    activity_main.xml:

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:padding="5dp">
    
        <AutoCompleteTextView
            android:layout_marginTop="20dp"
            android:id="@+id/text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:hint="type here..."
            android:dropDownWidth="300dp"/>
    
        <Button
            android:id="@+id/clear"
            android:layout_width="23dp"
            android:layout_height="23dp"
            android:layout_marginRight="10dp"
            android:layout_gravity="right|bottom"
            android:layout_marginBottom="10dp"
            android:background="@drawable/ic_close_black_24dp"
            android:onClick="clear"/>
    
    </FrameLayout>
    

    MainActivity.java:

    public class MainActivity extends AppCompatActivity {
    
        AutoCompleteTextView text;
        Button clear;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            text = (AutoCompleteTextView) findViewById(R.id.text);
    
            clear = (Button) findViewById(R.id.clear);
    
            clear.setVisibility(View.INVISIBLE);
    
            //close button visibility for manual typing
            text.addTextChangedListener(new TextWatcher() {
    
                @Override
                public void afterTextChanged(Editable s) {
                    //do nothing
                }
    
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    //do nothing
                }
    
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if(s.length() != 0) {
                        clear.setVisibility(View.VISIBLE);
                    } else {
                        clear.setVisibility(View.GONE);
                    }
                }
            });
    
            //sample array
            String[] array = {"alpha", "beta", "cupcake", "donut", "eclair", "froyo", "gingerbread", "honeycomb", "icecreamsandwich", "jellybean", "kitkat", "lollipop", "marshmallow"};
    
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,array);
    
            text.setThreshold(1);       //will start working from first character
    
            text.setAdapter(adapter);   //setting the adapter data into the AutoCompleteTextView
    
            //Shows drop down list on touch
            text.setOnTouchListener(new View.OnTouchListener(){
                @Override
                public boolean onTouch(View v, MotionEvent event){
                    text.showDropDown();
                    return false;
                }
            });
    
            //close button visibility for autocomplete text view selection
            text.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    
                @Override
                public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                    clear.setVisibility(View.VISIBLE);
                }
    
                @Override
                public void onNothingSelected(AdapterView<?> arg0) {
                    clear.setVisibility(View.GONE);
                }
    
            });
    
        }
    
        public void clear(View view) {
            text.setText("");
            clear.setVisibility(View.GONE);
        }
    }
    

    【讨论】:

      【解决方案3】:
      <FrameLayout
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_weight="1">
      
              <AutoCompleteTextView
                  android:id="@+id/desart"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:layout_weight="1"
                  android:textSize="15sp" />
      
              <ImageButton
                  android:id="@+id/clean"
                  android:layout_width="20dp"
                  android:layout_height="20dp"
                  android:adjustViewBounds="true"
                  android:layout_gravity="right|center_vertical"
                  android:background="@drawable/clean_state_button"
                  android:scaleType="center"/>
      
       </FrameLayout>
      

      Autocompletetextview with image button

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-22
        • 1970-01-01
        • 1970-01-01
        • 2017-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多