You are on page 1of 15

Bài tập thực hành Phát triển ứng dụng trên thiết bị di động 1

LAB 06: THIẾT KẾ GIAO DIỆN (tt)


MỤC TIÊU
• Sử dụng các Layout trong Xamarin.
• Sử dụng các thành phần giao diện có dạng danh sách:
o Custom ListView
o GridView

NỘI DUNG

Ví dụ 1: Tạo ListView với các tùy chỉnh nâng cao


Cơ chế hoạt động của ListView
Data source: nguồn dữ liệu cần nạp vào listView
Adapter: bộ phận chịu trách nhiệm load dữ liệu từ Data Source lên ListView

Chúng ta có thể sử dụng Android.Resource.Layout để thiết lập giao diện cho ListView,
các layout có sẵn bao gồm:

• TestListItem
• SimpleListItem1
• SimpleListItem2
• SimpleSelectableListItem
• SimpleListItemActivated1
• SimpleListItemActivated2
• SimpleListItemChecked
• SimpleListItemMultipleChoice
• SimpleListItemSingleChoice
Bài tập thực hành Phát triển ứng dụng trên thiết bị di động 2

• TwoLineListItem
• ActivityListItem
• SimpleExpandableListItem

Mỗi layout sẽ được thiết kế sẵn với các giao diện như sau:
Bài tập thực hành Phát triển ứng dụng trên thiết bị di động 3

Ngoài ra, chúng ta có thể tự tạo layout riêng cho ListView:

Bước 0: Tạo project Xamarin Android

Bước 1: Tạo file Resources/Layout/CustomView.xml:

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#FFDAFF7F"
android:padding="8dp">
<LinearLayout android:id="@+id/Text"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dip">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FF7F3300"
android:textSize="20dip"
android:textStyle="italic"
/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14dip"
android:textColor="#FF267F00"
Bài tập thực hành Phát triển ứng dụng trên thiết bị di động 4

android:paddingLeft="100dip"
/>
</LinearLayout>
<ImageView
android:id="@+id/imageView"
android:layout_width="48dp"
android:layout_height="48dp"
android:padding="5dp"
android:layout_alignParentRight="true" />
</RelativeLayout >

Bước 2: Tạo lớp TableItem.cs:

Click phải vào tên project, sau đó chọn Add -> New Item…

Chọn mục Class và đặt tên:


Bài tập thực hành Phát triển ứng dụng trên thiết bị di động 5

Kết quả sau khi tạo:

Nội dung file TableItem.cs:


namespace CustomListView
{
Bài tập thực hành Phát triển ứng dụng trên thiết bị di động 6

public class TableItem


{
public string Heading;
public string SubHeading;
public int id;
public TableItem(string Heading,string SubHeading, int id)
{
this.Heading = Heading;
this.SubHeading = SubHeading;
this.id = id;
}
}
}

Bước 3: Tạo lớp HomeScreenAdapter.cs (làm tương tự như bước 2)

using Android.App;
using Android.Views;
using Android.Widget;
using System.Collections.Generic;
namespace CustomListView
{
public class HomeScreenAdapter : BaseAdapter<TableItem>
{
List<TableItem> items;
Activity context;
public HomeScreenAdapter(Activity context, List<TableItem> items)
: base()
{
this.context = context;
this.items = items;
}
public override long GetItemId(int position)
{
return position;
}
Bài tập thực hành Phát triển ứng dụng trên thiết bị di động 7

public override TableItem this[int position]


{
get { return items[position]; }
}
public override int Count
{
get { return items.Count; }
}
public override View GetView(int position, View convertView, ViewGroup
parent)
{
var item = items[position];
View view = convertView;
if (view == null) // no view to re-use, create new
view = context.LayoutInflater.Inflate(Resource.Layout.CustomView,
null);
view.FindViewById<TextView>(Resource.Id.textView1).Text = item.Heading;
view.FindViewById<TextView>(Resource.Id.textView2).Text =
item.SubHeading;

view.FindViewById<ImageView>(Resource.Id.imageView).SetImageResource(item.id);
return view;
}
}

Bước 4: Bổ sung 6 file hình ảnh vào thư mục drawable

Lần lượt đặt tên các file hình ảnh là: image1.jpg , image2.jpg … image6.jpg
Bài tập thực hành Phát triển ứng dụng trên thiết bị di động 8

Bước 5: Tạo giao diện chính cho ứng dụng (file activity_main.xml):

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>

Bước 6: Viết code trong file MainActivity.cs:

using Android.App;
using Android.OS;
using Android.Runtime;
using Android.Widget;
using AndroidX.AppCompat.App;
using System.Collections.Generic;

namespace CustomListView
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher =
true)]
public class MainActivity : AppCompatActivity
{
ListView listview;
List<TableItem> tableItems = new List<TableItem>();
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);

listview = FindViewById<ListView>(Resource.Id.listview);

LoadData(); // nạp dữ liệu vào biến tableItems:

listview.Adapter = new HomeScreenAdapter(this, tableItems);

// Xử lý sự kiện click chọn trên ListView:


listview.ItemClick += Listview_ItemClick;
}

private void Listview_ItemClick(object sender,


AdapterView.ItemClickEventArgs e)
{
string str = tableItems[e.Position].Heading;
Toast.MakeText(this,str,ToastLength.Short).Show();
Bài tập thực hành Phát triển ứng dụng trên thiết bị di động 9

private void LoadData()


{
tableItems.Add(new TableItem("Vegetables", "65 items",
Resource.Drawable.image1));
tableItems.Add(new TableItem("Fruits", "17 items",
Resource.Drawable.image2));
tableItems.Add(new TableItem("Flower Buds", "5 items",
Resource.Drawable.image3));
tableItems.Add(new TableItem("Legumes", "33 items",
Resource.Drawable.image4));
tableItems.Add(new TableItem("Bulds", "18 items",
Resource.Drawable.image5));
tableItems.Add(new TableItem("Tubers", "43 items",
Resource.Drawable.image6));
}
public override void OnRequestPermissionsResult(int requestCode, string[]
permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode,
permissions, grantResults);

base.OnRequestPermissionsResult(requestCode, permissions, grantResults);


}
}
}
Bài tập thực hành Phát triển ứng dụng trên thiết bị di động 10

Bước 7: Kết quả khi chạy chương trình

Ngoải ra, chúng ta có thể Thêm, Xóa, Sửa các item trên ListView bằng cách sau:
1. Gọi các phương thức thêm/xóa/sửa datasource
2. Gọi phương thức adapter.NotifyDataSetChanged();
Ví dụ 2: GridView
Cách xây dựng tương tự như ListView

Bước 1: Tạo project

Bước 2: Thiết kế giao diện chính cho ứng dụng (file activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
Bài tập thực hành Phát triển ứng dụng trên thiết bị di động 11

android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="@+id/gridView"
android:numColumns="2"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>

Bước 3: Đưa hình ảnh vào thư mục drawable

(có thể đưa nhiều hơn ứng dụng sinh động hơn)

Bước 4: Tạo class TableItem.cs

namespace CustomListView
{
public class TableItem
{
public string Heading;
public string SubHeading;
public int id;
public TableItem(string Heading,string SubHeading, int id)
{
this.Heading = Heading;
this.SubHeading = SubHeading;
this.id = id;
}
}
}
Bài tập thực hành Phát triển ứng dụng trên thiết bị di động 12

Bước 5: Tạo class HomeScreenAdapter.cs

using Android.App;
using Android.Views;
using Android.Widget;
using System.Collections.Generic;
namespace CustomListView
{
public class HomeScreenAdapter : BaseAdapter<TableItem>
{
List<TableItem> items;
Activity context;
public HomeScreenAdapter(Activity context, List<TableItem> items)
: base()
{
this.context = context;
this.items = items;
}
public override long GetItemId(int position)
{
return position;
}
public override TableItem this[int position]
{
get { return items[position]; }
}
public override int Count
{
get { return items.Count; }
}
public override View GetView(int position, View convertView, ViewGroup
parent)
{
var item = items[position];
View view = convertView;
if (view == null) // no view to re-use, create new
view = context.LayoutInflater.Inflate(Resource.Layout.CustomView,
null);
//view.FindViewById<TextView>(Resource.Id.textView1).Text =
item.Heading;
//view.FindViewById<TextView>(Resource.Id.textView2).Text =
item.SubHeading;

view.FindViewById<ImageView>(Resource.Id.imageView).SetImageResource(item.id);
return view;
}
}
}

Bước 6: Tạo Layout cho từng Item (file Layout / CustomView.xml)

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#FFDAFF7F"
Bài tập thực hành Phát triển ứng dụng trên thiết bị di động 13

android:padding="8dp">
<ImageView
android:id="@+id/imageView"
android:layout_width="150dp"
android:layout_height="150dp"
android:padding="5dp"
android:layout_alignParentRight="true" />
</RelativeLayout >

Bước 7: Viết code cho file MainActivity.cs

using Android.App;
using Android.OS;
using Android.Runtime;
using Android.Widget;
using AndroidX.AppCompat.App;
using System.Collections.Generic;

namespace CustomListView
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher =
true)]
public class MainActivity : AppCompatActivity
{
GridView gridView;
List<TableItem> tableItems = new List<TableItem>();
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);

gridView = FindViewById<GridView>(Resource.Id.gridView);

LoadData(); // nạp dữ liệu vào biến tableItems:

gridView.Adapter = new HomeScreenAdapter(this, tableItems);

// Xử lý sự kiện click chọn trên ListView:


gridView.ItemClick += GridView_ItemClick; ;
}

private void GridView_ItemClick(object sender,


AdapterView.ItemClickEventArgs e)
{
string str = tableItems[e.Position].Heading;
Toast.MakeText(this, str, ToastLength.Short).Show();
}

private void LoadData()


{
tableItems.Add(new TableItem("Vegetables", "65 items",
Resource.Drawable.image1));
Bài tập thực hành Phát triển ứng dụng trên thiết bị di động 14

tableItems.Add(new TableItem("Fruits", "17 items",


Resource.Drawable.image2));
tableItems.Add(new TableItem("Flower Buds", "5 items",
Resource.Drawable.image3));
tableItems.Add(new TableItem("Legumes", "33 items",
Resource.Drawable.image4));
tableItems.Add(new TableItem("Bulds", "18 items",
Resource.Drawable.image5));
tableItems.Add(new TableItem("Tubers", "43 items",
Resource.Drawable.image6));
}
public override void OnRequestPermissionsResult(int requestCode, string[]
permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode,
permissions, grantResults);

base.OnRequestPermissionsResult(requestCode, permissions, grantResults);


}
}
}

Bước 8: Chạy thử chương trình


Bài tập thực hành Phát triển ứng dụng trên thiết bị di động 15

*** HẾT ***

You might also like