如何仅在 xamarin.forms 中使用微调项选择打开另一个 activity?

How can I open another activity using spinner item selection in xamarin.forms only?

我试过了,看起来大多数搜索结果都提到了 Android 工作室。我正在使用 visual studio、xamarin 表单。

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

    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.my_array, Android.Resource.Layout.SimpleSpinnerItem);

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

微调器加载完美,但项目选择方法在加载时打开 activity。

private void spinner_ItemSelected (object sender, AdapterView.ItemSelectedEventArgs e)
{
 SetContentView (Resource.Layout.page1);
}

如何最好地加载特定项目选择的 activity。 注意:项目在 Strings.xml.

中引用

因为Spinner初始化时默认选择第一项,所以会触发spinner_ItemSelected

你可以在你的spinner_ItemSelected方法中加入条件判断:

private void spinner_ItemSelected (object sender, AdapterView.ItemSelectedEventArgs e)
 {
    var index = e.Parent.SelectedItemPosition; //base on the select position
    var obj = e.Parent.SelectedItem; // base on the selectitem value(string) 
    // xxx is your conditions
    if(index == xxx)
     {
      SetContentView (Resource.Layout.page1);
     }
    // or 
    if(obj.ToString().Equals("xxx"))
     {
      SetContentView (Resource.Layout.page1);
     }
 }