65.9K
CodeProject 正在变化。 阅读更多。
Home

在 Xamarin.Android 和 Visual Studio 中使用适配器显示数据

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2014年7月25日

CPOL

4分钟阅读

viewsIcon

45579

在 Xamarin.Android 和 Visual Studio 中使用适配器显示数据

引言

对于大多数 Xamarin.Android 应用程序,您需要显示某种类型的数据。 这些数据可能来自数据库、XML 或其他技术。 如果您已经使用 .NET Framework 开发了 Windows 或 Web 应用程序,那么您会熟悉使用 UI 控件并在运行时从不同来源的数据填充这些控件。 Android 类似地允许开发人员使用数据填充 UI 控件,但是在使用 Android 实现此目的的方式上存在差异。 本文的目的是向您展示如何使用 Xamarin.AndroidVisual Studio 使用数据填充 Android UI 控件。

假设

出于本文的目的,我将假定读者熟悉创建 Android 屏幕布局和在 C# 中实现类。

背景

Adapter 类是 UI 控件和数据源之间的桥梁。 在 Android 开发领域,所有 UI 控件统称为 ViewView 是所有 UI 组件的基本构建块。 Adapter 类返回 View 的实例。 当用于显示项目列表时,Adapter 将为每个数据项返回一个 View,即,为项目列表中的每一行返回一个 View

开发人员可以在数据显示之前操作数据的表示形式。 例如,如果数据包含一个 BIT 类型来表示 True / False 条件,开发人员可以从 View 返回单词 TRUEFALSE,而不是显示其原始 BIT 值。

非常简单的适配器示例 - 项目列表

以下示例演示如何显示一个非常简单的项目列表。

  • 描述
  • Make
  • 模型
  • 数量

为了使文章简洁明了,我将使用 XML 数据来填充列表。 以下是底层 XML 的示例。

<GOODS>
    <GOOD>
        <DESCRIPTION>Description1</DESCRIPTION>
        <MAKE>Item1</MAKE>
        <MODEL>Model1</MODEL>
        <QUANTITY>1</QUANTITY>
    </GOOD>
    <GOOD>
        <DESCRIPTION>Description2</DESCRIPTION>
        <MAKE>Item2</MAKE>
        <MODEL>Model2</MODEL>
        <QUANTITY>2</QUANTITY>
</GOODS>

数据由商品列表组成。 每个商品项目都有相关的描述、制造商、型号和数量。

创建屏幕

首先,我们需要一个屏幕来显示我们的项目列表。 以下是在 Visual Studio 的设计器中屏幕外观的屏幕截图。

以下是 ListView 元素的 Android XML (AXML) 代码列表,即,实际上将商品列表渲染到屏幕的 View

<ListView
            p1:minWidth="25px"
            p1:minHeight="25px"
            p1:layout_width="match_parent"
            p1:layout_height="match_parent"
            p1:textAppearance="?android:attr/textAppearanceMedium"
            p1:layout_below="@id/textView1"
            p1:id="@+id/GoodsList" />

以下是完整的屏幕布局 (AXML) 列表,显示了列标题和其他 UI 元素。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:p1="http://schemas.android.com/apk/res/android"
    p1:orientation="vertical"
    p1:minWidth="25px"
    p1:minHeight="25px"
    p1:id="@+id/Goods"
    p1:layout_width="fill_parent"
    p1:layout_height="fill_parent">
    <RelativeLayout
        p1:minWidth="25px"
        p1:minHeight="25px"
        p1:layout_width="wrap_content"
        p1:layout_height="fill_parent"
        p1:id="@+id/relativeLayout1"
        p1:padding="5dp"
        p1:layout_weight="0.5">
        <Button
            p1:text="Next"
            p1:layout_width="wrap_content"
            p1:layout_height="wrap_content"
            p1:id="@+id/btnListGoods"
            p1:drawableRight="@android:drawable/ic_media_next"
            p1:layout_alignParentBottom="true"
            p1:layout_alignParentRight="true" />
        <TextView
            p1:text="List of Goods"
            p1:textAppearance="?android:attr/textAppearanceLarge"
            p1:id="@+id/textView1"
            p1:layout_width="wrap_content"
            p1:layout_height="wrap_content" />
        <ListView
            p1:minWidth="25px"
            p1:minHeight="25px"
            p1:layout_width="match_parent"
            p1:layout_height="match_parent"
            p1:textAppearance="?android:attr/textAppearanceMedium"
            p1:layout_below="@id/textView1"
            p1:id="@+id/GoodsList" />
        <TextView
            p1:text="Description"
            p1:textAppearance="?android:attr/textAppearanceSmall"
            p1:layout_width="wrap_content"
            p1:layout_height="wrap_content"
            p1:layout_toRightOf="@id/textView2"
            p1:id="@+id/textView2"
            p1:layout_marginTop="35.2dp" />
        <TextView
            p1:text="Make"
            p1:textAppearance="?android:attr/textAppearanceSmall"
            p1:layout_width="wrap_content"
            p1:layout_height="wrap_content"
            p1:layout_toRightOf="@id/textView2"
            p1:id="@+id/textView3"
            p1:layout_marginTop="35.2dp"
            p1:layout_marginLeft="129.1dp" />
        <TextView
            p1:text="Model"
            p1:textAppearance="?android:attr/textAppearanceSmall"
            p1:layout_width="wrap_content"
            p1:layout_height="wrap_content"
            p1:layout_toRightOf="@id/textView3"
            p1:id="@+id/textView4"
            p1:layout_marginTop="35.2dp"
            p1:layout_marginLeft="167.5dp" />
        <TextView
            p1:text="Serial Numer"
            p1:textAppearance="?android:attr/textAppearanceSmall"
            p1:layout_width="wrap_content"
            p1:layout_height="wrap_content"
            p1:layout_toRightOf="@id/textView4"
            p1:id="@+id/textView5"
            p1:layout_marginTop="35.2dp"
            p1:layout_marginLeft="159.4dp" />
        <TextView
            p1:text="Characteristics"
            p1:textAppearance="?android:attr/textAppearanceSmall"
            p1:layout_width="wrap_content"
            p1:layout_height="wrap_content"
            p1:layout_toRightOf="@id/textView5"
            p1:id="@+id/textView6"
            p1:layout_marginTop="35.2dp"
            p1:layout_marginLeft="116.3dp" />
        <TextView
            p1:text="Quantity"
            p1:textAppearance="?android:attr/textAppearanceSmall"
            p1:layout_width="wrap_content"
            p1:layout_height="wrap_content"
            p1:layout_toRightOf="@id/textView6"
            p1:id="@+id/textView7"
            p1:layout_marginLeft="85.8dp"
            p1:layout_marginTop="35.2dp" />
    </RelativeLayout>
</LinearLayout>

创建商品列表类

接下来,我们需要实现 GoodGoods 类,因为这些将构成文章的基础。 Good 类表示将出现在列表中的单个项目。 Goods 类表示 Good 对象的列表,即 List<Good>

public class Good
{
        public string Description;
        public string Make;
        public string Model;
        public int Quantity = 1;
        
        public Good()
        {

        }
}

public class Goods : List<Good>
{
        public Goods()
        {

        }

	//constructor capable of creating a new list from XML
        public Goods(XElement xRoot)
        {
            if (xRoot == null || !xRoot.HasElements) return;

            var xGoodList = xRoot.Descendants().ToList();

            foreach (Good cg in xGoodList.Select(xGood => new Good(xGood)).Where(cg => !string.IsNullOrEmpty(cg.Description)))
            {
                Add(cg);
            }
        }
}

现在,我们有一个可以显示商品列表的屏幕布局,并且我们有 GoodGoods 类的类定义,这些类定义将用于填充屏幕布局上显示的列表。

创建适配器类

现在我们需要定义一个 Adapter。 如前所述,Adapter 是 UI View 元素和底层 XML 数据之间的桥梁。 在此示例中,Adapter 将充当我们的 XML 数据和 ListView 之间的桥梁。

我们将从 Android BaseAdapter 类派生我们的 Adpater 类,该类是所有 Adapter 类的公共基类。

using System;
using System.Collections.Generic;
using System.Globalization;

using Android.App;
using Android.Graphics;
using Android.Views;
using Android.Widget;

using Application.Model;

namespace Application.Adapters
{
    public class GoodsAdapter : BaseAdapter<Good>
    {
        private readonly List<Good> _list;
        private readonly Activity _context;

        public GoodsAdapter(Activity context, List<Good> list)
        {
            _context = context;
            _list = list;
        }

        public List<Good> GetList()
        {
            return _list;
        } 

        public override long GetItemId(int position)
        {
            return position;
        }

        public override int Count
        {
            get { return _list.Count; }
        }

        public override Good this[int position]
        {
            get { return _list[position]; }
        }

        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            TextView view = new TextView(_context);

            const string space = " ";
            string description = this[position].Description.PadRight(25, Convert.ToChar(space)).Substring(0, 25);
            string make = this[position].Make.PadRight(25, Convert.ToChar(space)).Substring(0, 25);
            string model = this[position].Model.PadRight(25, Convert.ToChar(space)).Substring(0, 25);
            string quantity = this[position].Quantity.ToString(CultureInfo.InvariantCulture).PadRight(5, Convert.ToChar(space)).Substring(0, 5);
            
            //alternate the row colours and set the text foreground / background colours
            var bgColor = position % 2 == 0
                              ? Color.White
                              : Color.LightGray;

            view.SetBackgroundColor(bgColor);
            view.SetTextColor(Color.Black);
            view.SetTypeface(Typeface.Monospace, TypefaceStyle.Bold);
            view.SetHeight(50);

            view.Text = description +
                        make +
                        model +
                        quantity;
            
            return view;
        }

    }
}

关于我们的 Adapter 类需要注意的事项。

  • 该类派生自 BaseAdapter
  • 商品列表和应用程序上下文通过构造函数传入并存储为类属性(分别为 _list_context
  • GetView() 方法是主要的方法,负责为列表中的每个项目返回一个 View 实例,即,此方法返回列表中的一行

填充商品列表

剩下的唯一步骤是使用 XML 数据填充 Adapter 并在屏幕上显示项目列表。 您可以将类似于以下内容的代码添加到您的 ActivityFragment 类中来实现此目的。

//we will assume xRoot contains a list of goods as per the structure described earlier in the article
Goods _goods = new XElement(xRoot);

var adapter = new GoodsAdapter(Activity, _goods);
var viewGoods = Activity.FindViewById<ListView>(Resource.Id.GoodsList);
viewGoods.Adapter = adapter;

摘要

希望本文为您提供了足够的信息,以便您开始在 Xamarin.Android 应用程序中创建自己的 Adapter 类。 如果您希望我进一步详细说明本文中的任何内容,请随时发表评论。

© . All rights reserved.