App中常用的控件——下拉列表(Spinner),提供特定选择供用户选择
Spinner每次只能选择一个部件,它的选项来自于与之相关联的适配器(apater)中。
MainActivity.java
package cn.lixyz.widgetdemo; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MainActivity extends Activity { Spinner spinner; String[] strArr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); spinner = (Spinner) findViewById(R.id.spinner); //创建一个适配器,并加入数据源 strArr = this.getResources().getStringArray(R.array.payType); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, strArr); //为Spinner设置设配齐 spinner.setAdapter(adapter); //设置加载spinner时不选择选项 spinner.setSelection(0, true); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Log.d("TEST", "选择的是: " + strArr[position]); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } }
acitivyt_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:orientation="vertical"> <Spinner android:id="@+id/spinner" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
string.xml
<resources> <string name="app_name">WidgetDemo</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> <string-array name="payType"> <item>请选择消费类型</item> <item>衣</item> <item>食</item> <item>住</item> <item>行</item> </string-array> </resources>
运行结果: