Search code examples
androidautocompletetextviewandroid-toast

How to create Toast from AutoCompleteTextView selected item?


I am a newbie android learner. I am trying to create toast when the item from the AutoCompleteTextView is selected by the user. I am reading the value from strings.xml ,which is working fine but i am confused how do I (what even handler) i needed to create toast. below is my code 1- activity.xml

<AutoCompleteTextView android:id="@+id/myautocomplete"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="110dp"
/>

strings.xml
<string-array name="termsarray">
<item>emulator</item>
<item>ant</item>
<item>string.xml</item>
    <item>activity</item>
    <item>workspace</item>
    <item>adt</item>
    <item>manifest.xml</item>
    <item>package</item>
    <item>layout</item>
    <item>toast</item>
    <item>adb</item>
</string-array> 
//activity.java
public class TermActivity extends Activity {

 String[] categories;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    categories=getResources().getStringArray(R.array.termsarray);
    setContentView(R.layout.activity_term);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_dropdown_item_1line, categories);
    AutoCompleteTextView textView = 
            (AutoCompleteTextView) findViewById(R.id.myautocomplete);
    textView.setThreshold(3);
    textView.setAdapter(adapter); 

}

Solution

  • Handle that on a listener.Try this:

    textView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                  Toast.makeText(context, "Position clicked: " + position, Toast.LENGTH_SHORT).show();
          }
    });