androidxamarin.androidmultiautocompletetextview

MultiAutoCompleteTextView android restrict user from selecting same value multiple times


MultiAutoCompleteTextView android how to restrict user from selecting same value multiple times?


Solution

  • You could check the values which selected in ItemClick event.

    I make a code sample for you.

    layout2.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <MultiAutoCompleteTextView
    android:id="@+id/multiAutoCompleteTextView1"
                             android:layout_width="match_parent"
                             android:layout_height="wrap_content"/>
    </LinearLayout>
    

    MainActivity.cs

     var multiAutoCompleteTextView1 = FindViewById<MultiAutoCompleteTextView>(Resource.Id.multiAutoCompleteTextView1);
    
            string[] arraydata = { "apple1", "apple2", "shanghai1", "shanghai2" };
    
            ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, arraydata);
            multiAutoCompleteTextView1.Adapter = adapter;
            multiAutoCompleteTextView1.SetTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
    
            string PreviousText = string.Empty;
    
            multiAutoCompleteTextView1.ItemClick += (s, e) =>
            {
                var currentText = multiAutoCompleteTextView1.Text;
                var currentList = currentText.Replace(" ","").Split(',');
                var length = currentList.Length;
                if (length > 2)
                {
                    for (int i = 0; i < length - 1; i++)
                    {
                        if (i < length - 2)
                        {
                            if (currentList[i] == currentList[length - 2])
                            {
                                multiAutoCompleteTextView1.Text = PreviousText;
                                //do the something when you select the same value
                            }
                        }
    
                    }
    
                }
    
                PreviousText = multiAutoCompleteTextView1.Text;
            };
    

    In the sample code, i reset the value of MultiAutoCompleteTextView when select the same value. enter image description here