Android: AutoCompleteTextView hide soft keyboard

ChrisGeo picture ChrisGeo · Feb 4, 2013 · Viewed 30.1k times · Source

I have an AutoCompleteTextView which as usual provides suggestions after a user types 3 letters. I want once once I touch the suggestion list to hide the soft keyboard. What I have done below with the table layout hides the keyboard only when clicking anywhere but the suggestion list.

XML

<TableRow
    android:id="@+id/tableRow2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center" >

    <AutoCompleteTextView
        android:id="@+id/auto_insert_meds"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="15"
        android:inputType="textVisiblePassword|textMultiLine"
        android:scrollHorizontally="false"
        android:text=""
        android:textSize="16sp" />
</TableRow>

Java

TableLayout tbl = (TableLayout) findViewById(R.id.main_table);
tbl.setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        in.hideSoftInputFromWindow(v.getWindowToken(), 0);
        return true;
    }
});

XML for custom list

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/medlist_linear_layout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

        <TextView
        android:id="@+id/med_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scrollHorizontally="false"
        android:padding="3dp"
        android:textColor="@android:color/white" />

</LinearLayout>

Answer

user948620 picture user948620 · Feb 4, 2013

Use OnItemClickListener. Hope this works :)

AutoCompleteTextView text = (AutoCompleteTextView) findViewById(R.id.auto_insert_meds);

text.setOnItemClickListener(new OnItemClickListener() {

  @Override
  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    in.hideSoftInputFromWindow(arg1.getWindowToken(), 0);

  }

});

UPDATED

Use this

in.hideSoftInputFromWindow(arg1.getApplicationWindowToken(), 0);

instead of -

in.hideSoftInputFromWindow(arg1.getWindowToken(), 0);