Xamarin 简明教程

Xamarin - Android Widgets

Date Picker

这是一个用于显示日期的小组件。在此示例中,我们将创建一个日期选择器,它会在文本视图中显示设置的日期。

This is a widget used to display date. In this example, we are going to create a date picker which displays the set date on a text view.

首先,创建一个新项目并将其称为 datePickerExample 。打开 Main.axml 并创建一个 datepickertextview 和一个 button

First of all, create a new project and call it datePickerExample. Open Main.axml and create a datepicker, textview, and a button.

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   android:orientation = "vertical"
   android:layout_width = "fill_parent"
   android:layout_height = "fill_parent">
   <DatePicker
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:id = "@+id/datePicker1" />
   <TextView
      android:text = "Current Date"
      android:textAppearance = "?android:attr/textAppearanceLarge"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:id = "@+id/txtShowDate" />
   <Button
      android:text = "Select Date"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:id = "@+id/btnSetDate" />
</LinearLayout>

接下来,转到 Mainactivity.cs 。我们首先在 mainActivity:Activity 类中创建一个文本视图的私有实例。

Next, go to Mainactivity.cs. We first create a private instance of a textview inside the mainActivity:Activity class.

该实例将用于存储选定的日期或默认日期。

The instance will be used to store the date selected or the default date.

private TextView showCurrentDate;

接下来,在 setContentView() 方法之后添加以下代码。

Next, add the following code after setContentView() method.

DatePicker pickDate = FindViewById<DatePicker>(Resource.Id.datePicker1);
showCurrentDate = FindViewById<TextView>(Resource.Id.txtShowDate);
setCurrentDate();
Button button = FindViewById<Button>(Resource.Id.btnSetDate);
button.Click += delegate {
   showCurrentDate.Text = String.Format("{0}/{1}/{2}",
      pickDate.Month, pickDate.DayOfMonth, pickDate.Year);
};

在上面的代码中,我们通过使用 FindViewById 类从我们的 main.axml 文件中找到它们,从而引用了我们的日期选择器、文本视图和按钮。

In the above code, we have referenced our datepicker, textview, and button by finding them from our main.axml file using FindViewById class.

引用后,我们设置了按钮单击事件,该单击事件负责将选定的日期从日期选择器传递到文本视图。

After referencing, we set the button click event which is responsible for passing the selected date from the date picker to the textview.

接下来,我们创建 setCurrentDate() 方法,以将默认当前日期显示到我们的文本视图。以下代码说明了如何执行此操作。

Next, we create the setCurrentDate() method for displaying the default current date to our textview. The following code explains how it is done.

private void setCurrentDate() {
   string TodaysDate = string.Format("{0}",
      DateTime.Now.ToString("M/d/yyyy").PadLeft(2, '0'));
   showCurrentDate.Text = TodaysDate;
}

DateTime.Now.ToString() 类将今天的日期时间绑定到字符串对象。

DateTime.Now.ToString() class binds today’s time to a string object.

现在,构建并运行该应用程序。它应该显示以下输出:

Now, build and run the App. It should display the following output −

datepicker

Time Picker

时间选择器是一个用于显示时间以及允许用户选择和设置时间的小组件。我们将创建一个基本的 time picker 应用程序,该应用程序会显示时间,还允许用户更改时间。

Time Picker is a widget used to display time as well as allowing a user to pick and set time. We are going to create a basic time picker app that displays the time and also allows a user to change the time.

转到 main.axml 并添加一个新按钮、文本视图和时间选择器,如下面的代码中所示。

Go to main.axml and add a new button, textview, and a time picker as shown in the following code.

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   android:orientation = "vertical"
   android:background = "#d3d3d3"
   android:layout_width = "fill_parent"
   android:layout_height = "fill_parent">
   <TimePicker
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:id = "@+id/timePicker1" />
   <TextView
      android:text = "Time"
      android:textAppearance = "?android:attr/textAppearanceLarge"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:id = "@+id/txt_showTime"
      android:textColor = "@android:color/black" />
   <Button
      android:text = "Set Time"
      android:layout_width = "200dp"
      android:layout_height = "wrap_content"
      android:id = "@+id/btnSetTime"
      android:textColor = "@android:color/black"
      android:background = "@android:color/holo_green_dark" />
</LinearLayout>

转到 MainActivity.cs 来添加将设置日期显示在创建的文本视图上的功能。

Go to MainActivity.cs to add the functionality for displaying a set date on the textview we created.

public class MainActivity : Activity {

   private TextView showCurrentTime;

   protected override void OnCreate(Bundle bundle) {

      base.OnCreate(bundle);
      SetContentView(Resource.Layout.Main);
      TimePicker Tpicker = FindViewById<TimePicker>(Resource.Id.timePicker1);
      showCurrentTime = FindViewById<TextView>(Resource.Id.txt_showTime);
      setCurrentTime();
      Button button = FindViewById<Button>(Resource.Id.btnSetTime);

      button.Click += delegate {
         showCurrentTime.Text = String.Format("{0}:{1}",
            Tpicker.CurrentHour, Tpicker.CurrentMinute);
      };
   }
   private void setCurrentTime() {
      string time = string.Format("{0}",
         DateTime.Now.ToString("HH:mm").PadLeft(2, '0'));
      showCurrentTime.Text = time;
   }
}

在上面的代码中,我们首先通过 FindViewById<> 类引用 timepickerset time 按钮和文本视图以显示时间。然后,我们为“设置时间”按钮创建了一个单击事件,该事件会在单击时将时间设置为某人选择的时间。默认情况下,它显示当前系统时间。

In the above code, we first referenced the timepicker,set time button and the textview for showing time through the FindViewById<> class. We then created a click event for the set time button which on click sets the time to the time selected by a person. By default, it shows the current system time.

setCurrentTime() 方法类初始化 txt_showTime textview 显示当前时间。

The setCurrentTime() method class initializes the txt_showTime textview to display the current time.

现在,构建并运行您的应用程序。它应显示以下输出 −

Now, build and run your application. It should display the following output −

time picker

Spinner

旋钮是用来自一组中选择一个选项的小部件。它相当于一个下拉框/组合框。首先,创建一个新项目并称其为 Spinner App Tutorial

A spinner is a widget used to select one option from a set. It is an equivalent of a dropdown/Combo box. First of all, create a new project and call it Spinner App Tutorial.

layout folder 下打开 Main.axml 并创建一个 spinner

Open Main.axml under the layout folder and create a new spinner.

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   android:orientation = "vertical"
   android:layout_width = "fill_parent"
   android:layout_height = "fill_parent">
   <Spinner
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:id = "@+id/spinner1"
      android:prompt = "@string/daysOfWeek" />
</LinearLayout>

打开 values folderStrings.xml 文件,并添加以下代码来创建 spinner items

Open Strings.xml file located under values folder and add the following code to create the spinner items.

<resources>
  <string name = "daysOfWeek">Choose a planet</string>
  <string-array name = "days_array">
      <item>Sunday</item>
      <item>Monday</item>
      <item>Tuesday</item>
      <item>Wednesday</item>
      <item>Thursday</item>
      <item>Friday</item>
      <item>Saturday</item>
      <item>Sunday</item>
   </string-array>
</resources>

接下来,打开 MainActivity.cs 以添加用于显示已选星期的功能。

Next, open MainActivity.cs to add the functionality for displaying the selected day of the week.

protected override void OnCreate(Bundle bundle) {
   base.OnCreate(bundle);
   // Set our view from the "main" layout resource
   SetContentView(Resource.Layout.Main);
   Spinner spinnerDays = FindViewById<Spinner>(Resource.Id.spinner1);
   spinnerDays.ItemSelected += new EventHandler
      <AdapterView.ItemSelectedEventArgs>(SelectedDay);
   var adapter = ArrayAdapter.CreateFromResource(this,
      Resource.Array.days_array, Android.Resource.Layout.SimpleSpinnerItem);
   adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropD ownItem);
   spinnerDays.Adapter = adapter;
}
private void SelectedDay(object sender, AdapterView.ItemSelectedEventArgs e) {
   Spinner spinner = (Spinner)sender;
   string toast = string.Format("The selected
      day is {0}", spinner.GetItemAtPosition(e.Position));
   Toast.MakeText(this, toast, ToastLength.Long).Show();
}

现在,构建并运行此应用程序。它应显示以下输出 −

Now, build and run the application. It should display the following output −

spinner app

在上述代码中,我们引用了 main.axml 文件中创建的旋钮,方法是通过 FindViewById<> 类。然后,我们创建了一个 arrayAdapter() ,该类用于绑定 strings.xml 类的数组项。

In the above code, we referenced the spinner we created in our main.axml file through the FindViewById<> class. We then created a new arrayAdapter() which we used to bind our array items from the strings.xml class.

最后,我们创建了 SelectedDay() 方法,该类用于显示已选星期。

Finally we created the method SelectedDay() which we used to display the selected day of the week.