[英]How do I go back to the top of the code?
我一直在學習C#,並且正在創建一個應用程序。
我嘗試了goto語句,但是標簽“超出范圍”,我希望它使我回到原來的布局,發現我需要回到代碼頂部。
namespace TheAppOfJack
{
[Activity(Label = "The App Of Jack", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
int count = 1;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Button button1 = FindViewById<Button>(Resource.Id.MyButton);
button1.Click += delegate { button1.Text = string.Format("You have clicked this random button {0} times ( ͡° ͜ʖ ͡°)", count++); };
Button button2 = FindViewById<Button>(Resource.Id.button1);
button2.Click += delegate
{
SetContentView(Resource.Layout.Gallery);
Button button3 = FindViewById<Button>(Resource.Id.back);
button3.Click += delegate { SetContentView(Resource.Layout.Main); };
Button button4 = FindViewById<Button>(Resource.Id.next1);
button4.Click += delegate
{
SetContentView(Resource.Layout.Gallery2);
button3.Click += delegate { SetContentView(Resource.Layout.Main); };
Button button5 = FindViewById<Button>(Resource.Id.next2);
button5.Click += delegate
{
SetContentView(Resource.Layout.Gallery3);
Button button6 = FindViewById<Button>(Resource.Id.home);
button6.Click += delegate {
//this is where i want the code to send me back to the top };
};
};
};
}
}
}
您嘗試的方式不是Android的工作方式。 您無法在“版式”之間導航,而是在具有與其關聯的布局的活動之間導航。 此導航使用StartActivity()
方法完成。
MainActivity
是啟動應用程序時將顯示的第一個活動。 它的關聯布局(在這里被命名為Main
)應該只有一個按鈕,它將帶您進入下一個屏幕。 假設其ID為btnForActivity2
。 您的MainActivity
OnCreate
將如下所示:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Button btn = FindViewById<Button>(Resource.Id.btnForActivity2);
btn.Click += delegate
{
StartActivity (typeof(MyActivity2));
};
}
在MyActivity2
類中,假設您希望有兩個按鈕將您帶到兩個新活動。 假設一個活動稱為MyActivity3
,另一個活動稱為MyActivity4
。 在這種情況下,您的MyActivity2
的OnCreate
方法將如下所示:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.MyActivity2Layout);
Button btn = FindViewById<Button>(Resource.Id.btnForActivity3);
btn.Click += delegate
{
StartActivity (typeof(MyActivity3));
};
btn = FindViewById<Button>(Resource.Id.btnForActivity4);
btn.Click += delegate
{
StartActivity (typeof(MyActivity4));
};
}
這就是Android中基本導航的工作方式。
順便說一句,您可能已經注意到我還沒有談論過“后退”按鈕。 這是因為我從未明確實現它,因為與iOS設備不同,Android設備具有專門用於此目的的按鈕。 但是,如果您必須具有一個使您返回上一活動的按鈕,則只需調用this.Finish();
應該足夠了。 一旦為活動調用Finish()
,它就會從活動堆棧的頂部刪除,並且下面的活動變為可見。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.