AutoCompleteTextView autoCompleteTextView = new AutoCompleteTextView(context);
autoCompleteTextView.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
String[] suggestions = {"Apple", "Banana", "Cherry", "Coconut"}; ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_dropdown_item_1line, suggestions); autoCompleteTextView.setAdapter(adapter);
parentLayout.addView(autoCompleteTextView);
完整示例代码:
LinearLayout parentLayout = findViewById(R.id.parent_layout);
AutoCompleteTextView autoCompleteTextView = new AutoCompleteTextView(context); autoCompleteTextView.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
String[] suggestions = {"Apple", "Banana", "Cherry", "Coconut"}; ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_dropdown_item_1line, suggestions); autoCompleteTextView.setAdapter(adapter);
parentLayout.addView(autoCompleteTextView);