Visual Studio 跨平台开发实战(5) - Xamarin Android 多页面应用程式开发

来源:互联网 发布:golang defer 编辑:程序博客网 时间:2024/05/24 05:47
前言

大部份的Android 都具有实体或虚拟的Back鍵. 因此在处理多页面应用程式时, 与先前所介绍的iOS Navigation controller 比较起来会简单许多.

1. 开启Visual Studio 并新增Android Application 专案并命名为Lab4-MultiScreen

 

 

2. 在Layout资料夹中新增Second.axml

 

在Second.axml 中拖放1个TextView并标示此为第2个Activity

 

2. 在专案底下新增一个SecondActivity.cs. 在OnCreate事件中选写以下程式码:

view source
print?
1SetContentView(Resource.Layout.Second);

3. 开启Activity1.cs, 在class name的地方按滑鼠右鍵=>重构=>重新命名. 将类别名称改为FirstActivity. 记得在方案总管中的档名也一并改为FirstActivity.cs

 

4. 开启Main.axml, 在画面中放置1个Button并指定Text属性值为”Load Second Activity”并将id 的属性值变更为”@+id/ShowSecond”

5. 开启FirstActivity.cs, 在OnCreate事件中撰写以下程式码:

view source
print?
01//载入页面
02 
03SetContentView(Resource.Layout.Main);
04 
05//宣告并取得按钮物件, 并在按钮的click事件处理中载入SecondActivity
06 
07Button button = FindViewById< Button >(Resource.Id.showSecond);
08 
09button.Click += delegate
10 
11{…….按钮处理函式}

Button的click处理函式中, 我们将使用3种方法来载入SecondActivity.

  • 方法一: 使用内建的StartActivity方法, 程式码如下:
view source
print?
1//呼叫其他Activity的第一种方法(隐含的建立Intent)
2 
3StartActivity(typeof(SecondActivity));

  • 方法二: 建立Intent, 然后使用StartActivity载入其他SecondActivity. 程式码如下:
view source
print?
1//呼叫其他Activity的第二种法, 建立Intent, 然后使用StartActivity载入其他Activity
2 
3var second = newIntent(this,typeof(SecondActivity));
4 
5StartActivity(second);

  • 方法三: 建立Intent, 并透过Intent.PutExtra载入Activity并传入参数. 程式码如下:
view source
print?
1//使用Intent.PutExtra载入Activity并传入参数
2 
3var second = newIntent(this,typeof(SecondActivity));
4 
5second.PutExtra("FirstData","Data from FirstActivity");
6 
7StartActivity(second);

上述的3种方式, 第1个跟第2个是一样的, 使用第1种方式, 会隐含简历一个Intent物件。

6. 执行专案并检视结果.

7. 透过上述的第3个方法, 可以像QueryString般传递参数到下一个Activity. 现在我们开启SecondActivity.cs. 透过Intent的GetStringExtra方法来取得参数的值. 在Oncreate方法中撰写以下程式码:

view source
print?
01//载入页面
02 
03SetContentView(Resource.Layout.Second);
04 
05//宣告并取得TextView物件
06 
07var label = FindViewById<textview>(Resource.Id.screen2Label);
08 
09//透过Intent.GetStringExtra取得从前一个Activity所传来的讯息
10 
11label.Text = Intent.GetStringExtra("FirstData") ??"Data not available";</textview>

在上述程式码中, 我们透过Intent的GetStringExtra(“参数名称”)来取得字串型別的参数. 事实上还可以透过类似的方法取得不同型別的参数值. 如下圖所示:

而??陈述式则是用来判断是否为Null的方便写法. 若取出的值为Null则显示后面的字串.

8. 执行专案并检视结果, 如下图所示

结语

在本篇文章中, 我们介绍Android 应用程式在多页面中的切换, 相较于iOS, Android 对于多页面的处理较为方便. 另外在Android中也提供Tab控制项在多页面之间进行切换.

 

本文转自:Terry's IT Note

了解更多移动跨平台解决方案,请访问:http://xamarin.csdn.net

 

0 0
原创粉丝点击