如何创建下拉列表? [英] How to create a drop-down list?
问题描述
如何创建下拉列表?我已经尝试过 ScrollView,但它并不是我所需要的.
How can I create a drop-down list? I've tried a ScrollView but it's not exactly what I need.
推荐答案
简单/优雅/我是怎么做的:
simple / elegant / how I do it:
预览:
XML:
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/btn_dropdown"
android:spinnerMode="dropdown"/>
spinnerMode
设置为 dropdown
是 androids 制作下拉菜单的方式.(https://developer.android.com/reference/android/widget/Spinner#attr_android:spinnerMode)
spinnerMode
set to dropdown
is androids way to make a dropdown. (https://developer.android.com/reference/android/widget/Spinner#attr_android:spinnerMode)
Java:
//get the spinner from the xml.
Spinner dropdown = findViewById(R.id.spinner1);
//create a list of items for the spinner.
String[] items = new String[]{"1", "2", "three"};
//create an adapter to describe how the items are displayed, adapters are used in several places in android.
//There are multiple variations of this, but this is the basic variant.
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
//set the spinners adapter to the previously created one.
dropdown.setAdapter(adapter);
文档:
这是基础知识,但还有更多内容需要通过实验自学.https://developer.android.com/guide/topics/ui/controls/spinner.html
This is the basics but there is more to be self taught with experimentation. https://developer.android.com/guide/topics/ui/controls/spinner.html
- 您可以将 setOnItemSelectedListener 用于此.(https://developer.android.com/guide/topics/ui/controls/spinner.html#SelectListener)
- 您可以从 xml 添加字符串列表.(https://developer.android.com/guide/topics/ui/controls/spinner.html#Populate)
- 此视图有一个 appCompat 版本.(https://developer.android.com/reference/androidx/appcompat/widget/AppCompatSpinner)
这篇关于如何创建下拉列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!