如何在Xamarin android中将文本和图像添加到网格视图中

问题描述 投票:1回答:1

我想创建一个网格视图,其中共有8列,包含图像和文本。第一次我尝试单独使用动态图像并且成功但是在添加文本视图后我遇到了错误。

我的网格视图适配器就像

public class ImageAdapter : BaseAdapter
{
    Context context;

    public ImageAdapter(Context c)
    {
        context = c;
    }

    public override int Count
    {
        get { return thumbIds.Length; }
    }

    public override Java.Lang.Object GetItem(int position)
    {
        return null;
    }

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

    // create a new ImageView for each item referenced by the Adapter
    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        ImageView imageView;

        if (convertView == null)  //to set layout
        {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(context);
            imageView.LayoutParameters = new GridView.LayoutParams(85, 85);
            imageView.SetScaleType(ImageView.ScaleType.CenterCrop);
            imageView.SetPadding(8, 8, 8, 8);
        }
        else
        {
            imageView = (ImageView)convertView;
        }

        imageView.SetImageResource(thumbIds[position]);
        return imageView;
    }

    // references to our images
    int[] thumbIds = {
    Resource.Drawable.rsz_logo, Resource.Drawable.rsz_logo,   //my image
    Resource.Drawable.rsz_logo, Resource.Drawable.rsz_logo,
    Resource.Drawable.rsz_logo, Resource.Drawable.rsz_logo,
    Resource.Drawable.rsz_logo, Resource.Drawable.rsz_logo
};
}

enter image description here我的代码在这里,这只会产生没有文字的图像。

c# gridview xamarin.android
1个回答
1
投票

您可以使用TextViewImageView在axml中自定义您的itemlayout,如下所示:

创建layout_item.axml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="horizontal"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:gravity = "center">
  <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView" />

   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Text"
  />
</LinearLayout>

然后在适配器的GetView方法中:

public override View GetView(int position, View convertView, ViewGroup parent)
     {
       ImageView imageView;
       TextView textView;
       if (convertView == null)
         {
            convertView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.layout_item, null);
            imageView = convertView.FindViewById<ImageView>(Resource.Id.imageView);
            textView = convertView.FindViewById<TextView>(Resource.Id.textView);
         }
            //imageView.SetImageResource;
            //textView.Text;
         return convertView;

    }
© www.soinside.com 2019 - 2024. All rights reserved.