【Android】5.4 下拉框(Spinner)

分类:C#、Android、VS2015;

创建日期:2016-02-07

下拉列表框Spinner的用法和WinForms中ComboBox的用法非常相似,在Android应用中使用频次也相当高,因此必须熟练掌握它的基本用法。

一般在单独的XML中声明下拉列表可选项,这样更具有通用性。

示例5—Demo05Spinner

1、运行截图

image

2、添加demo05_Spinner.axml文件

在layout文件夹下添加该文件。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:text="选择课程:"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip"
        android:id="@+id/textView1" />
    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/spinner1" />
    <Button
        android:text="确定"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/buttonOK" />
</LinearLayout>

记住:每次修改布局文件后都要保存。否则在.cs文件中键入代码时无法利用智能提示找到对应的控件。

3、修改String.xml文件

打开values文件夹下的String.xml文件,将其改为下面的内容:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  ……
  <string-array name="CourseItems">
    <item>数据结构</item>
    <item>操作系统</item>
    <item>计算机网络</item>
  </string-array>
</resources>

这一步只是为了让你明白如何将String.xml中定义的数组和设计界面相关联。实际上在.cs文件中直接定义更方便。

4、添加Demo05Spinner.cs文件

在SrcActivity文件夹下添加该文件。

using Android.App;
using Android.OS;
using Android.Widget;

namespace ch05demos.SrcActivity
{
    [Activity(Label = "SpinnerDemo")]
    public class Demo05Spinner : Activity
    {
        private Spinner spinner;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.demo05_Spinner);
            spinner = FindViewById<Spinner>(Resource.Id.spinner1);
            var adapter = ArrayAdapter.CreateFromResource(
                    this, Resource.Array.CourseItems,
                    Android.Resource.Layout.SimpleSpinnerItem);
            adapter.SetDropDownViewResource(
               Android.Resource.Layout.SimpleSpinnerDropDownItem);
            spinner.Adapter = adapter;
            spinner.ItemSelected += Spinner_ItemSelected;
            var btn = FindViewById<Button>(Resource.Id.buttonOK);
            btn.Click += delegate
            {
                string s = spinner.SelectedItem.ToString();
                Toast.MakeText(this, s, ToastLength.Long).Show();
            };
        }

        private void Spinner_ItemSelected(object sender,
            AdapterView.ItemSelectedEventArgs e)
        {
            string s = string.Format("所选课程为:{0}",
                  spinner.GetItemAtPosition(e.Position));
            Toast.MakeText(this, s, ToastLength.Long).Show();
        }
    }
}

运行观察结果。

原文地址:https://www.cnblogs.com/rainmj/p/5184555.html