Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 C# 與 VS2015 寫 Android:MyDemos 專案結構與主視覺實作

編輯:關於 Android 開發

簡介

系統升級到 Win10 之後,重新建立了一個名為 MyDemos 的專案,並把前面七章的內容合併進來。這一篇說明合併後的專案結構,以及主視覺相關的程式碼。技術棧是 C# + Visual Studio 2015 + Xamarin。

專案結構

MyDemos 的資源檔與 Activity 檔建立方式在先前章節已有說明,此處不再重複。整體採用「一個專案收攏所有章節範例」的組織方式,主視覺用可展開清單做為章節目錄,點選子項即跳進對應的範例頁面。

一、修改 Main.axml

主視覺由三個部分組成:標題、來源連結、以及一個 ExpandableListView。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:id="@+id/heading1"
        android:text="用C#和VS2015編寫Android手機App"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#00000000"
        android:textSize="16dp"
        android:textColor="#FFFF0000"
        android:padding="5dp"
        android:gravity="center_horizontal" />

    <TextView
        android:id="@+id/heading2"
        android:text="www.cnblogs.com/rainmj/"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#00000000"
        android:textSize="14dp"
        android:textColor="#FF267F00"
        android:gravity="center_horizontal"
        android:paddingBottom="5dp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dip"
        android:background="#FF909090"
        android:layout_marginBottom="5dp" />

    <ExpandableListView
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/expandableListView1" />
</LinearLayout>

二、MyApplication.cs

放在專案根目錄。這裡同時示範了 Application 子類別的標準寫法——那個 (IntPtr, JniHandleOwnership) 的建構子是 Xamarin 的必要配對。

using System;
using Android.App;
using Android.Runtime;
using Com.Baidu.Mapapi;

namespace MyDemos
{
    [Application]
    public class MyApplication : Application
    {
        // 必須提供此建構函數
        public MyApplication(IntPtr javaReference, JniHandleOwnership transfer)
            : base(javaReference, transfer)
        {
        }

        public override void OnCreate()
        {
            base.OnCreate();
            SDKInitializer.Initialize(ApplicationContext);
        }
    }
}

三、MyBroadcastReceiver.cs

用來接收 SDK 的驗證狀態廣播,並把結果回寫到主視覺的 heading2 上。

using Android.Content;
using Android.Widget;
using Com.Baidu.Mapapi;
using Android.Util;

namespace MyDemos
{
    [BroadcastReceiver]
    public class MyBroadcastReceiver : BroadcastReceiver
    {
        private MainActivity mainActivity;

        // 必須提供無參數的建構函數
        public MyBroadcastReceiver()
        {
        }

        public MyBroadcastReceiver(MainActivity bdMapMain)
        {
            mainActivity = bdMapMain;
        }

        public override void OnReceive(Context context, Intent intent)
        {
            string s = intent.Action;
            TextView text = mainActivity.FindViewById<TextView>(Resource.Id.heading2);
            switch (s)
            {
                case SDKInitializer.SdkBroadtcastActionStringPermissionCheckError:
                    text.Text = "Andoid SDK(v3.7.1)key 驗證出錯!";
                    break;
                case SDKInitializer.SdkBroadtcastActionStringPermissionCheckOk:
                    Log.Debug("MainActivity", "百度Andoid SDK(v3.7.1)key 驗證成功!");
                    break;
                case SDKInitializer.SdkBroadcastActionStringNetworkError:
                    text.Text = "Andoid SDK(v3.7.1)key 驗證失敗:網絡出錯!";
                    break;
            }
        }
    }
}

四、MyExpandableListAdapter.cs

這段程式碼有兩個值得注意的設計:一是把「章」與「章內項目」定義成 Chapter 與 ChItem 兩個資料類別,Adapter 只依賴這份資料模型;二是用 ChItem.type 存放範例頁面的 Type,點擊時直接用它 StartActivity,省掉一層 Intent 對應表。

using System;
using System.Collections.Generic;
using Android.Content;
using Android.Views;
using Android.Widget;
using Android.Graphics;

namespace MyDemos
{
    public class Chapter
    {
        public string ChapterName { get; set; }
        public ChItem[] ChapterItems { get; set; }
    }

    public class ChItem
    {
        public Type type { get; set; }
        public string Title { get; set; }
        public string Desc { get; set; }
    }

    public class MyExpandableListAdapter : BaseExpandableListAdapter
    {
        private readonly Context context;
        private readonly IList<Chapter> chapter;

        public MyExpandableListAdapter(Context context, IList<Chapter> chapter)
        {
            this.context = context;
            this.chapter = chapter;
        }

        public override int GroupCount
        {
            get { return chapter.Count; }
        }

        public override bool HasStableIds
        {
            get { return true; }
        }

        public override Java.Lang.Object GetChild(int groupPosition, int childPosition)
        {
            return null;
        }

        public override long GetChildId(int groupPosition, int childPosition)
        {
            return childPosition;
        }

        public override int GetChildrenCount(int groupPosition)
        {
            var ch = chapter[groupPosition];
            return ch.ChapterItems.Length;
        }

        public override View GetChildView(int groupPosition, int childPosition,
                                          bool isLastChild, View convertView, ViewGroup parent)
        {
            var view = convertView;
            if (view == null)
            {
                var inflater = context.GetSystemService(Context.LayoutInflaterService)
                               as LayoutInflater;
                view = inflater.Inflate(Android.Resource.Layout.SimpleExpandableListItem2, null);
            }
            var ch = chapter[groupPosition];
            var chItem = ch.ChapterItems[childPosition];

            TextView textView = view.FindViewById<TextView>(Android.Resource.Id.Text1);
            textView.Text = chItem.Title;
            textView.SetTextColor(Color.Blue);
            textView.TextSize = 12;

            textView = view.FindViewById<TextView>(Android.Resource.Id.Text2);
            textView.Text = chItem.Desc;
            textView.TextSize = 9;
            return view;
        }

        public override Java.Lang.Object GetGroup(int groupPosition)
        {
            return null;
        }

        public override long GetGroupId(int groupPosition)
        {
            return groupPosition;
        }

        public override View GetGroupView(int groupPosition, bool isExpanded,
                                          View convertView, ViewGroup parent)
        {
            var view = convertView;
            if (view == null)
            {
                var inflater = context.GetSystemService(Context.LayoutInflaterService)
                               as LayoutInflater;
                view = inflater.Inflate(Android.Resource.Layout.SimpleExpandableListItem1, null);
            }
            var ch = chapter[groupPosition];
            TextView textView = view.FindViewById<TextView>(Android.Resource.Id.Text1);
            textView.Text = ch.ChapterName;
            textView.TextSize = 14;
            return view;
        }

        public override bool IsChildSelectable(int groupPosition, int childPosition)
        {
            return true;
        }
    }
}

五、MainActivity.cs

using Android.App;
using Android.Content;
using Android.Widget;
using Android.OS;
using System.Collections.Generic;
using Com.Baidu.Mapapi.Model;
using Com.Baidu.Mapapi;
using MyDemos.SrcDemos;

namespace MyDemos
{
    [Activity(Label = "MyDemos--毛毛雨的博客樂園", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        private IList<Chapter> chItems;
        private MyBroadcastReceiver myReceiver;

        // 自定義的中心點經緯度
        public static readonly LatLng MyLatLng = new LatLng(34.824635, 114.315745);

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);

            // 註冊廣播監聽
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.AddAction(SDKInitializer.SdkBroadtcastActionStringPermissionCheckOk);
            intentFilter.AddAction(SDKInitializer.SdkBroadtcastActionStringPermissionCheckError);
            intentFilter.AddAction(SDKInitializer.SdkBroadcastActionStringNetworkError);
            myReceiver = new MyBroadcastReceiver(this);
            RegisterReceiver(myReceiver, intentFilter);

            CreateChItems();
            var adapter = new MyExpandableListAdapter(this, chItems);
            var expandableListView1 = FindViewById<ExpandableListView>(Resource.Id.expandableListView1);
            expandableListView1.SetAdapter(adapter);
            expandableListView1.ChildClick += (sender, args) =>
            {
                var type = chItems[args.GroupPosition]
                                 .ChapterItems[args.ChildPosition].type;
                if (type != null)
                {
                    StartActivity(new Intent(this, type));
                }
            };
        }

        protected override void OnDestroy()
        {
            base.OnDestroy();
            // 取消廣播監聽
            UnregisterReceiver(myReceiver);
        }

        private void CreateChItems()
        {
            chItems = new List<Chapter>();

            chItems.Add(new Chapter()
            {
                ChapterName = "第1章 開發環境安裝和配置",
                ChapterItems = new ChItem[]
                {
                    new ChItem { type = null, Title = "本章無示例", Desc = "" },
                }
            });

            chItems.Add(new Chapter()
            {
                ChapterName = "第2章 Android應用程序的調試和部署",
                ChapterItems = new ChItem[]
                {
                    new ChItem
                    {
                        type = typeof(ch0201Main),
                        Title = "例2-1 Phoneword",
                        Desc = "演示如何導航到另一個界面以及如何撥號"
                    },
                }
            });

            // 後面章節的內容與前面類似,此處省略……
        }
    }
}

後續擴充方式

這個結構的好處在於擴充成本極低。以後要加入新章節的範例,只要在 CreateChItems() 中補一段即可:

chItems.Add(new Chapter()
{
    ChapterName = "……",
    ChapterItems = new ChItem[]
    {
        new ChItem { type = typeof(你的Activity), Title = "……", Desc = "……" },
    }
});

其他部分完全不需要更動。目錄的呈現、點擊跳轉、廣播註冊都已經在框架層處理好了,新增範例只是往資料清單裡加一筆資料而已。

下一篇接著說明第 8 章的內容。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved