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

时间:2019-03-15 04:30:50

标签: c# gridview xamarin.android

我想创建一个网格视图,其中总共有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 我的代码在这里,这只会生成没有文本的图像。

1 个答案:

答案 0 :(得分:1)

您可以像这样使用TextViewImageView在axml中自定义项目布局:

创建 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;

    }
相关问题