展示
源码
<GridView
android:id="@+id/grid_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="3" />
<!-- Resources/layout/grid_item.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ImageView
android:id="@+id/icon"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/avatar" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ProsperLee"/>
</LinearLayout>
-
Scripts/GridViewAdapter.cs
using System.Collections.Generic;
using Android.Content;
using Android.Views;
using Android.Widget;
using Java.Lang;
namespace android_by_csharp.Scripts
{
public class GridInfo
{
public readonly int Icon;
public readonly string Text;
public GridInfo(int icon, string text)
{
Icon = icon;
Text = text;
}
}
public class GridViewAdapter : BaseAdapter
{
private readonly List<GridInfo> _gridInfos;
private readonly LayoutInflater _context;
public GridViewAdapter(Context context, List<GridInfo> gridInfos)
{
_context = LayoutInflater.FromContext(context);
_gridInfos = gridInfos;
}
public override Object GetItem(int position)
{
return null;
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
convertView ??= _context.Inflate(Resource.Layout.grid_item, parent, false);
var icon = (ImageView)convertView?.FindViewById(Resource.Id.icon);
var text = (TextView)convertView?.FindViewById(Resource.Id.text);
icon?.SetImageResource(_gridInfos[position].Icon);
if (text != null) text.Text = _gridInfos[position].Text;
return convertView;
}
public override int Count => _gridInfos.Count;
}
}
-
MainActivity.cs
var gridView = (GridView)FindViewById(Resource.Id.grid_view);
var list = new List<GridInfo>
{
new GridInfo((int)Resource.Drawable.avatar, "ProsperLee"),
new GridInfo((int)Resource.Drawable.avatar, "ProsperLee"),
new GridInfo((int)Resource.Drawable.avatar, "ProsperLee"),
new GridInfo((int)Resource.Drawable.avatar, "ProsperLee"),
new GridInfo((int)Resource.Drawable.avatar, "ProsperLee"),
new GridInfo((int)Resource.Drawable.avatar, "ProsperLee"),
new GridInfo((int)Resource.Drawable.avatar, "ProsperLee"),
new GridInfo((int)Resource.Drawable.avatar, "ProsperLee"),
new GridInfo((int)Resource.Drawable.avatar, "ProsperLee"),
new GridInfo((int)Resource.Drawable.avatar, "Lee")
};
var gridViewAdapter = new GridViewAdapter(this, list);
if (gridView != null) gridView.Adapter = gridViewAdapter;