Monday, 28 October 2013

Android: AutoCompleteTextView show all when no text entered and Show/Hide in Onclick


It looks like editable AutoCompleteTextView  with toggling option and it shows all options when no data is entered.

Here is CustomAutoCompleteTextView.Java

package com.example.myfirstapp;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.AutoCompleteTextView;

public class CustomAutoCompleteTextView extends AutoCompleteTextView {

    private Boolean _isDropDownShowing;
    public Boolean get_isDropDownShowing() {
        return _isDropDownShowing;
    }

    public void set_isDropDownShowing(Boolean _isDropDownShowing) {
        this._isDropDownShowing = _isDropDownShowing;
    }

    public CustomAutoCompleteTextView(Context context) {
        super(context);
    }

    public CustomAutoCompleteTextView(Context arg0, AttributeSet arg1) {
        super(arg0, arg1);
    }

     public CustomAutoCompleteTextView(Context arg0, AttributeSet arg1, int arg2) {
            super(arg0, arg1, arg2);
        }
   
    @Override
    public boolean enoughToFilter() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction,
            Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        if (focused) {
            performFiltering(getText(), 0);
           
        }
    }
   
    }




Here is the code to utilize the above CustomAutoCompleteTextView control in my Activity.
List<String> listOfStrings = new ArrayList<String>();
        listOfStrings.add("Apple");
        listOfStrings.add("Ball");
        listOfStrings.add("Cat");
   
        final CustomAutoCompleteTextView actv = new CustomAutoCompleteTextView(this);
        actv.set_isDropDownShowing(false);
        actv.setOnClickListener(new View.OnClickListener() {
           
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(actv.get_isDropDownShowing())
                {
                    actv.dismissDropDown();
                    actv.set_isDropDownShowing(false);
                }
                else
                {
                    actv.showDropDown();
                    actv.set_isDropDownShowing(true);
                }
            }
        });
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,    listOfStrings);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        actv.setAdapter(dataAdapter);
        linearLayout.addView(new EditText(context));
        linearLayout.addView(actv);
    }

1 comment: