首页 > 解决方案 > 使用意图方法调用活动

问题描述

我知道 Android 操作系统需要 paramterles 构造函数来重新创建 Activity,如果需要,我可以使用 bundle 传递一些参数,如下所示:

private void OpenOtherActivityWindow_Click(object sender, EventArgs e)

{
      Intent nextActivity = new Intent(this, typeof(ThirdActivity));
      Dog mydog = new Dog("mydogName");
      Bundle bundle = new Bundle();
      bundle.PutSerializable("mydoggy", mydog);
      nextActivity.PutExtra("RowID", Convert.ToString(10));
      nextActivity.PutExtras(bundle);
      StartActivity(nextActivity);
}

[Activity(Label = "ThirdActivity")]
 public class ThirdActivity : Activity
 {
       protected override void OnCreate(Bundle savedInstanceState)
       {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.third);

            //Receive values if any from previous activity
            if (!Intent.HasExtra("mydoggy")) return;
            Dog tryme = (Dog)Intent.GetSerializableExtra("mydoggy");
            if (!Intent.HasExtra("RowID")) return;
            string text = Intent.GetStringExtra("RowID") ?? "0";
        }
}

尽管如此,是否有可能创建静态方法,该方法会从给定的参数为我返回意图,例如?:

static Intent CreateIntent(Dog dog, int rowID)

如果是这样,有人可以告诉我,那么它看起来与我的代码中显示的内容相反。

标签: c#xamarinxamarin.android

解决方案


我不知道你的细节ThirdActivity,但我可以通过创建一个简单的演示来实现类似的功能。你可以在这里查看代码。

   [Activity(Label = "MovieDetailActivity")]
public class MovieDetailActivity : Activity
{
    public  TextView textView;

    public  static MovieModel mMoviemodel;// define your model here

    public  static int mRowID;  // define a int variable mRowID


    public  static Intent createIntent(Context context, MovieModel movie, int rowID)
    {
        Intent intent = new Intent(context, typeof(MovieDetailActivity));
        //Pass parameters here

        mMoviemodel = movie; 
        mRowID = rowID;

        return intent;
    }


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

        // Create your application here
        SetContentView(Resource.Layout.detaillayout);

        textView = FindViewById<TextView>(Resource.Id.info_textview);

        textView.Text = "movie name:" + mMoviemodel.mMovieName + " text = " + mRowID;

    }
}

用法:

   // pass your Object model
    StartActivity( MovieDetailActivity.createIntent(this, movie,10));

推荐阅读