Xamarin Android 微调框Xamarin.Android Spinner

Spinner是显示用于选择项的下拉列表的小组件。Spinner is a widget that presents a drop-down list for selecting items. 本指南说明如何创建一个简单的应用程序,该应用程序在微调框中显示选项列表,然后是用于显示与所选选择关联的其他值的修改。This guide explains how to create a simple app that displays a list of choices in a Spinner, followed by modifications that display other values associated with the selected choice.

基本微调框Basic Spinner

在本教程的第一部分中,你将创建一个简单的微调小组件,用于显示行星列表。In the first part of this tutorial, you'll create a simple spinner widget that displays a list of planets. 选择了地球后,toast 消息会显示所选项目:When a planet is selected, a toast message displays the selected item:

HelloSpinner 应用的示例屏幕截图Example screenshots of HelloSpinner app

启动名为HelloSpinner的新项目。Start a new project named HelloSpinner.

打开Resources/Layout/main.axml并插入以下 XML:Open Resources/Layout/Main.axml and insert the following XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

请注意, TextViewandroid:text 属性和Spinnerandroid:prompt 特性都引用相同的字符串资源。Notice that the TextView's android:text attribute and the Spinner's android:prompt attribute both reference the same string resource. 此文本将表现为小组件的标题。This text behaves as a title for the widget. 应用到Spinner时,标题文本将显示在选择小组件时显示的选择对话框中。When applied to the Spinner, the title text will appear in the selection dialog that appears upon selecting the widget.

编辑资源/值/字符串 .xml ,并修改该文件,如下所示:Edit Resources/Values/Strings.xml and modify the file to look like this:

<?xml version="1.0" encoding="utf-8"?>
  <string name="app_name">HelloSpinner</string>
  <string name="planet_prompt">Choose a planet</string>
  <string-array name="planets_array">

第二个 <string> 元素定义了TextView并在上面的布局中Spinner引用的标题字符串。The second <string> element defines the title string referenced by the TextView and Spinner in the layout above. <string-array> 元素定义将在Spinner小组件中显示为列表的字符串列表。The <string-array> element defines the list of strings that will be displayed as the list in the Spinner widget.

现在,打开MainActivity.cs并添加以下 using 语句:Now open MainActivity.cs and add the following using statement:

using System;

接下来,为OnCreate())方法插入以下代码:Next, insert the following code for the OnCreate()) method:

protected override void OnCreate (Bundle bundle)
    base.OnCreate (bundle);

    // Set our view from the "Main" layout resource
    SetContentView (Resource.Layout.Main);

    Spinner spinner = FindViewById<Spinner> (Resource.Id.spinner);

    spinner.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs> (spinner_ItemSelected);
    var adapter = ArrayAdapter.CreateFromResource (
            this, Resource.Array.planets_array, Android.Resource.Layout.SimpleSpinnerItem);

    adapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem);
    spinner.Adapter = adapter;

Main.axml 布局设置为内容视图后,将从具有FindViewById<>(int)的布局中捕获Spinner小组件。After the Main.axml layout is set as the content view, the Spinner widget is captured from the layout with FindViewById<>(int). CreateFromResource()The CreateFromResource() 方法会创建一个新的ArrayAdapter,它将字符串数组中的每一项绑定到Spinner的初始外观(这是每个项在选择时在微调框中的显示方式)。method then creates a new ArrayAdapter, which binds each item in the string array to the initial appearance for the Spinner (which is how each item will appear in the spinner when selected). Resource.Array.planets_array ID 引用前面定义的 string-arrayAndroid.Resource.Layout.SimpleSpinnerItem ID 引用了平台定义的标准微调框的布局。The Resource.Array.planets_array ID references the string-array defined above and the Android.Resource.Layout.SimpleSpinnerItem ID references a layout for the standard spinner appearance, defined by the platform. SetDropDownViewResource 调用以定义打开小组件时每个项的外观。is called to define the appearance for each item when the widget is opened. 最后,通过设置Adapter属性,将ArrayAdapter设置为将其所有项与Spinner相关联。Finally, the ArrayAdapter is set to associate all of its items with the Spinner by setting the Adapter property.

现在提供了一个回调方法,该方法在从Spinner中选择某个项时 notifys 该应用程序。Now provide a callback method that notifys the application when an item has been selected from the Spinner. 此方法应如下所示:Here's what this method should look like:

private void spinner_ItemSelected (object sender, AdapterView.ItemSelectedEventArgs e)
    Spinner spinner = (Spinner)sender;
    string toast = string.Format ("The planet is {0}", spinner.GetItemAtPosition (e.Position));
    Toast.MakeText (this, toast, ToastLength.Long).Show ();

选择某个项后,会将发送方强制转换为Spinner ,以便可以访问项。When an item is selected, the sender is cast to a Spinner so that items can be accessed. 使用 ItemEventArgs上的 Position 属性,可以找出所选对象的文本,并使用它来显示ToastUsing the Position property on the ItemEventArgs, you can find out the text of the selected object, and use it to display a Toast.

运行应用程序;其外观应如下所示:Run the application; it should look like this:

屏幕截图,并选择 Mars 作为行星Screenshot example of Spinner with Mars selected as the planet

使用键/值对进行微调Spinner Using Key/Value Pairs

通常,需要使用 Spinner 显示与应用使用的某种数据相关联的键值。Often it is necessary to use Spinner to display key values that are associated with some kind of data used by your app. 由于 Spinner 不会直接使用键/值对,因此必须单独存储键/值对,用键值填充 Spinner,然后使用微调框中所选键的位置查找关联的数据值。Because Spinner does not work directly with key/value pairs, you must store the key/value pair separately, populate the Spinner with key values, then use the position of the selected key in the Spinner to look up the associated data value.

在以下步骤中,将修改HelloSpinner应用以显示所选行星的平均温度:In the following steps, the HelloSpinner app is modified to display the mean temperature for the selected planet:

将以下 using 语句添加到MainActivity.csAdd the following using statement to MainActivity.cs:

using System.Collections.Generic;

将以下实例变量添加到 MainActivity 类。Add the following instance variable to the MainActivity class. 此列表将保存行星的键/值对及其平均温度:This list will hold key/value pairs for the planets and their mean temperatures:

private List<KeyValuePair<string, string>> planets;

OnCreate 方法中,在声明 adapter 之前添加以下代码:In the OnCreate method, add the following code before adapter is declared:

planets = new List<KeyValuePair<string, string>>
    new KeyValuePair<string, string>("Mercury", "167 degrees C"),
    new KeyValuePair<string, string>("Venus", "464 degrees C"),
    new KeyValuePair<string, string>("Earth", "15 degrees C"),
    new KeyValuePair<string, string>("Mars", "-65 degrees C"),
    new KeyValuePair<string, string>("Jupiter" , "-110 degrees C"),
    new KeyValuePair<string, string>("Saturn", "-140 degrees C"),
    new KeyValuePair<string, string>("Uranus", "-195 degrees C"),
    new KeyValuePair<string, string>("Neptune", "-200 degrees C")

此代码会创建一个简单的行星商店,并为其关联的平均温度。This code creates a simple store for planets and their associated mean temperatures. (在实际应用中,数据库通常用于存储密钥及其关联的数据。)(In a real-world app, a database is typically used to store keys and their associated data.)

紧跟在上述代码后面,添加以下行以提取关键字并将其放入列表中(按顺序):Immediately after the above code, add the following lines to extract the keys and put them into a list (in order):

List<string> planetNames = new List<string>();
foreach (var item in planets)
    planetNames.Add (item.Key);

将此列表传递到 ArrayAdapter 构造函数(而不是 planets_array 资源):Pass this list to the ArrayAdapter constructor (instead of the planets_array resource):

var adapter = new ArrayAdapter<string>(this,
    Android.Resource.Layout.SimpleSpinnerItem, planetNames);

修改 spinner_ItemSelected 以便使用所选位置查找与所选行星关联的值(温度):Modify spinner_ItemSelected so that the selected position is used to look up the value (the temperature) associated with the selected planet:

private void spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
    Spinner spinner = (Spinner)sender;
    string toast = string.Format("The mean temperature for planet {0} is {1}",
        spinner.GetItemAtPosition(e.Position), planets[e.Position].Value);
    Toast.MakeText(this, toast, ToastLength.Long).Show();

运行应用程序;toast 应如下所示:Run the application; the toast should look like this:

显示温度的行星选择的示例Example of planet selection displaying temperature


此页面的某些部分是基于 Android 开源项目创建和共享的工作的修改,并根据 创造性 Commons 2.5 归属许可证中所述的术语使用。Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.