kaaaxcreators
kaaaxcreators

Reputation: 133

Xamarin.Android: Dynamic AutoCompleteTextView

I create an adapter:

// public
ArrayAdapter<string> adapter { get; set; }
List<string> autocomplete = new List<string>();
// OnCreate()
AutoCompleteTextView autoComplete = FindViewById<AutoCompleteTextView>(Resource.Id.autoCompleteTextView1);
adapter = new ArrayAdapter<string>(this, Resource.Layout.list_item, autocomplete);
autoComplete.Adapter = adapter;
autoComplete.Threshold = 5;

Here I want to change to adapter or add suggestions

// AfterTextChanged()
adapter.Clear(); // Clear Adapter (previous suggestions)
// Get Autocomplete from Locationiq und Deserialize it
List<AutoComplete> auto = await GetAutoComplete(FindViewById<AutoCompleteTextView>(Resource.Id.autoCompleteTextView1).Text, Encoding.UTF8.GetString(Convert.FromBase64String(locationiq)));
List<string> temp = new List<string>();
foreach (AutoComplete city in auto)
{
    temp.Add(city.display_place); // Show only the display place (not coordinates etc)
}
autocomplete = temp; // Change the List
adapter.NotifyDataSetChanged(); // Notify that data changed

If I create the List before the Adapter with static data, it works fine, but I cant get it to work with dynamic data

Source Code

Can somebody help me with this? I looked up many stuff, but I could find a working solution

Upvotes: 0

Views: 274

Answers (1)

Cherry Bu - MSFT
Cherry Bu - MSFT

Reputation: 10346

According to your description, you want to add dynamic List for AutoCompleteTextView, I create one simple sample that you can take a lok:

public class MainActivity : AppCompatActivity
{
    List<string> countries;
    ArrayAdapter adapter;
    AutoCompleteTextView textView;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.activity_main);

        countries = new List<string>() {
   "Afghanistan","Albania","Algeria","American Samoa","Andorra",
  "Vanuatu","Vatican City","Venezuela","Vietnam","Wallis and Futuna","Western Sahara",
  "Yemen","Yugoslavia","Zambia","Zimbabwe"
};
        textView = FindViewById<AutoCompleteTextView>(Resource.Id.autocomplete_country);
        adapter = new ArrayAdapter(this, Resource.Layout.list_item, countries) ;

        textView.Adapter = adapter;
        Button btnadd = FindViewById<Button>(Resource.Id.button1);
        btnadd.Click += Btnadd_Click;
        textView.Adapter = adapter;
    }

    private void Btnadd_Click(object sender, EventArgs e)
    {
        countries.Clear();

        countries = new List<string>()
      {
          "chinese","test","english"
      };
        adapter.AddAll(countries);
        adapter.NotifyDataSetChanged();
       


    }

Upvotes: 1

Related Questions