自訂 Application
namespace ApplicationLogin { // 一定要有 Application Attribute [Application] public class MyApplication : Android.App.Application { public string UserName { get; set; } public MyApplication(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { this.UserName = "Unkown"; } public override void OnCreate() { base.OnCreate(); Toast.MakeText(this, "執行 MyApplication", ToastLength.Long).Show(); } } }Loginlayout.axml
<?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" android:minWidth="25px" android:minHeight="25px"> <LinearLayout android:orientation="horizontal" android:minWidth="25px" android:minHeight="25px" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout1"> <TextView android:text="使用者名稱:" android:layout_width="wrap_content" android:layout_height="match_parent" android:id="@+id/textView1" android:textSize="20dp" android:gravity="center" /> <EditText android:layout_width="wrap_content" android:layout_height="match_parent" android:id="@+id/txtUserName" android:hint="請輸入使用者名稱" android:inputType="text" /> </LinearLayout> <LinearLayout android:orientation="horizontal" android:minWidth="25px" android:minHeight="25px" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout3"> <Button android:text="登錄" android:layout_width="wrap_content" android:layout_height="match_parent" android:id="@+id/btnLogin" /> </LinearLayout> </LinearLayout>Layout1.axml:沒有任何控件
<?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" />LoginActivity.cs
namespace ApplicationLogin { [Activity(Label = "ApplicationLogin", MainLauncher = true, Icon = "@drawable/icon")] public class LoginActivity : Activity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Loginlayout); FindViewById<Button>(Resource.Id.btnLogin).Click += (sender, e) => { MyApplication app = (MyApplication)this.Application; app.UserName = FindViewById<EditText>(Resource.Id.txtUserName).Text.Trim(); this.StartActivity(typeof(Activity1)); }; } } }Activity.cs
namespace ApplicationLogin { [Activity(Label = "Activity1")] public class Activity1 : Activity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); MyApplication app = (MyApplication)this.Application; Toast.MakeText(this, app.UserName, ToastLength.Long).Show(); } } }執行 App
在 Activity1 內把 MyApplication.UserName 資訊顯示出來
沒有留言:
張貼留言