[Xamarin] 客製化的ListView之章

2013-07-17

上次我們說到簡單的的SimpleExpandableListItem1 來做選單

Screenshot_2013-07-15-12-39-00_thumb[2]

老闆不會因為這樣而滿足的,因為總是希望一個獨一無二,而且漂亮的List 選單
這篇我們來看看如何實作最後結果為自訂每一個ListItem的選單
Screenshot_2013-07-17-12-54-24

1.首先我們先制定我們需要的物件模型,假設每一個UserInfo 都會有這些資料,我們就先建立好物件模型 UserInfo.cs


namespace SimpleTextList
{
    public class UserInfo
    {
        public string Title { get; set; }
        public string Desc { get; set; }
        public string Image { get; set; }
    }
}

再來其中每一個ListItem我們都建立一個對應的Layout( 範例檔名:UserListItemLayout.axml ,這當然是自己設計的)


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:id="@+id/linearContainer"
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="10dip">
        <TextView
            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#CDFFE7"
            android:textSize="20dip"
            android:textStyle="italic"
            android:text="User's Name" />
        <TextView
            android:id="@+id/tvDesc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="14dip"
            android:textColor="#E76DA9"
            android:paddingLeft="100dip"
            android:text="User's Desc" />
    </LinearLayout>
    <ImageView
        android:id="@+id/imgUser"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:padding="5dp"
        android:src="@drawable/Icon"
        android:layout_alignParentRight="true" />
</RelativeLayout>

預覽:
2013-07-17_121407

2.再來我們需要寫一個Class 其為ListAdapter 其繼承為 BaseAdapter ,簡單的說他就是在Android 中,你要處理這種貌似於List的Layout 因為框架問題,而且他已經預設幫你處理好render跟很多手勢等問題,所以直接繼承來使用,該範例我取名為 UserListAdapter.cs


using System.Collections.Generic;
using System.Net;
using Android.App;
using Android.Graphics;
using Android.Views;
using Android.Widget;
 
namespace SimpleTextList
{
    class UserListAdapter : BaseAdapter<UserInfo>
    {
        /// <summary>
        /// 所有UserInof 的資料
        /// </summary>
        List<UserInfo> items;
    
        Activity context;
 
        public UserListAdapter(Activity context, List<UserInfo> items)
            : base()
        {
            this.context = context;
            this.items = items;
        }
        public override long GetItemId(int position)
        {
            return position;
        }
        public override UserInfo this[int position]
        {
            get { return items[position]; }
        }
        public override int Count
        {
            get { return items.Count; }
        }
 
        /// <summary>
        /// 系統會呼叫 並且render.
        /// </summary>
        /// <param name="position"></param>
        /// <param name="convertView"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            var item = items[position];
            var view = convertView;
            if (view == null)
            {
                //使用自訂的UserListItemLayout
                view = context.LayoutInflater.Inflate(Resource.Layout.UserListItemLayout, null);
            }
 
            view.FindViewById<TextView>(Resource.Id.tvName).Text = item.Title;
            view.FindViewById<TextView>(Resource.Id.tvDesc).Text = item.Desc;
            var imageBitmap = GetImageBitmapFromUrl(item.Image);
            view.FindViewById<ImageView>(Resource.Id.imgUser).SetImageBitmap(GetImageBitmapFromUrl(item.Image));
 
            return view;
        }
 
        /// <summary>
        /// 因為圖片是網址,所以將其圖片download回來後轉為bitmap
        /// Get IamgeBitmap form url.
        /// code reference : http://forums.xamarin.com/discussion/4323/image-from-url-in-imageview
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private Bitmap GetImageBitmapFromUrl(string url)
        {
            Bitmap imageBitmap = null;
 
            using (var webClient = new WebClient())
            {
                var imageBytes = webClient.DownloadData(url);
                if (imageBytes != null && imageBytes.Length > 0)
                {
                    imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
                }
            }
 
            return imageBitmap;
        }
 
    }
}

其中除了GetImageBitmapFromUrl 其他function 因為繼承關係都是必須要實作的,因為我設定的圖片是從網路上面來,所以附上一支可以從網路抓圖下來轉bitmap的function ,也因為沒做cache 的關係,所以會慢一點,在這class 我們發現,他將我步驟1 的 UserInfo 以及 UserListItemLayout 產生綁定,並且render 出 View 讓android 系統去畫~

3.現在Adapter做好了我們就來呼叫 首先我們產生一個Layout 來放一個ListView來render UserListItemLatout
ChooseUserLayout.axml :


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <ListView
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/listViewMain" />
</LinearLayout>

接下來,就是他搭配的Activity 部分
ChooseUserActivity.cs :


using System.Collections.Generic;
using Android.App;
using Android.OS;
using Android.Widget;
 
namespace SimpleTextList
{
    [Activity(Label = "請選擇用戶")]
    public class ChooseUserActivity : Activity
    {
        private List<UserInfo> datas;
        ListView listView;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
 
            SetContentView(Resource.Layout.ChooseUserLayout);
 
            listView = FindViewById<ListView>(Resource.Id.listViewMain);
            //載入假資料
            datas = new List<UserInfo>();
            datas.Add(new UserInfo { Title = "Donma", Desc = "當麻許,業餘的code generator", Image = "http://graph.facebook.com/donma.hsu/picture" });
            datas.Add(new UserInfo { Title = "Tony Stark", Desc = "Genius, billionaire, playboy, philanthropist.", Image = "http://graph.facebook.com/tonystarkpage/picture" });
            datas.Add(new UserInfo { Title = "Black Widow", Desc = "Real Name - Natalia  Alianovna", Image = "http://graph.facebook.com/blackwidowmovie/picture" });
 
 
            listView.Adapter = new UserListAdapter(this, datas);
            listView.ItemClick += listView_ItemClick;
        }
 
        /// <summary>
        /// 點選item 後的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void listView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            Toast.MakeText(this, "你選擇了 " + datas[e.Position].Title, ToastLength.Short).Show();
        }
    }
}

在這裡,我們放入三筆假資料,並且指定說其主ListView 使用的Adapter 為 UserListAdapter(來自於步驟2),並且指定其點擊後toast 其UserInfo的Title

4.接下來就是主Activity 將步驟3的 ChooseUserActivity給叫起


var btnUserList = FindViewById<Button>(Resource.Id.btnUserList);
btnUserList.Click += delegate
{
    StartActivity(typeof(ChooseUserActivity));
};

結果:
Screenshot_2013-07-17-14-24-44


Source code:

參考文件:
http://developer.android.com/reference/android/widget/BaseAdapter.html
http://docs.xamarin.com/guides/android/user_interface/working_with_listviews_and_adapters
http://docs.xamarin.com/guides/android/user_interface/working_with_listviews_and_adapters/part_3_-_customizing_a_listview%27s_appearance


當麻許的超技八 2014 | Donma Hsu Design.