xamarin android图片url数组进入gridview

cig3rfwq  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(341)

我只想把resource.drawable.image改成url,但我不知道怎么做。我尝试使用位图的方法,但我不知道如何使它数组使用这种方法。这样做的目的是我想从数据库中获取数据并将其存储到我的数据库中 List<> 或数组,所以输出将如图所示。它在resource.drawable.image中运行良好,但我想转换为url值。
顺便说一下,我已经从数据库中存储了列id。我还尝试将数据库中的image\u link列存储到while循环中,并将其调用到我的列表中<>但出现错误。请参阅下面的代码-->fragment1.cs所有这些代码都正常工作。
fragment\u layout.axml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  <RelativeLayout
    android:padding="16dp"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <GridView
      android:id="@+id/grid_view_image_text"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:columnWidth="110dp"
      android:gravity="center"
      android:numColumns="auto_fit"/>
  </RelativeLayout>
  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical"
      android:layout_gravity="center" />
</FrameLayout>

gridview\ u layout.axml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  <ImageView
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_marginTop="15dp"
    android:id="@+id/imageViewGrid"/>
  <TextView
    android:layout_marginTop="5dp"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textViewGrid"/>
</LinearLayout>

customgridviewadapter.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.Lang;

namespace testing_code
{
    public class CustomGridViewAdapter : BaseAdapter
    {
        private Context context;
        private string[] gridViewString;
        private int[] gridViewImage;
        public CustomGridViewAdapter(Context context, string[] gridViewstr, int[] gridViewImage)
        {
            this.context = context;
            gridViewString = gridViewstr;
            this.gridViewImage = gridViewImage;
        }
        public override int Count
        {
            get
            {
                return gridViewString.Length;
            }
        }

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

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

        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            View view;
            LayoutInflater inflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService);
            if(convertView == null)
            {
                view = new View(context);
                view = inflater.Inflate(Resource.Layout.gridview_layout, null);
                TextView txtview = view.FindViewById<TextView>(Resource.Id.textViewGrid);
                ImageView imgview = view.FindViewById<ImageView>(Resource.Id.imageViewGrid);

                txtview.Text = gridViewString[position];
                imgview.SetImageResource(gridViewImage[position]);
            }
            else
            {
                view = (View)convertView;
            }
            return view;
        }

        //private Bitmap GetImageBitmapFromUrl(string url)
        //{
        //    Bitmap imageBitmap = null;

        //    using (var webClient = new WebClient())
        //    {
        //        var imageBytes = webClient.DownloadData(url);
        //        if (imageBytes != null && imageBytes.Length > 0)
        //        {
        //            imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
        //        }
        //    }

        //    return imageBitmap;
        //}
    }
}

碎片1.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using SupportFragment = Android.Support.V4.App.Fragment;
using Android.Support.Design.Widget;
using Android.Support.V7.App;
using Android.Support.V4.Widget;
using Android.Support.V4.App;
using MySql.Data.MySqlClient;
using System.Data;

namespace testing_code
{
    public class Fragment1 : SupportFragment
    {
        MySqlConnection conn = new MySqlConnection();

        string query = "server=localhost;port=3306;database=dbsample;user id=root;password=123";

        GridView gridview;

        //string[] gridviewstring = {
        //        "location", "sound", "note"
        //};

        //int[] imgview =
        //{
        //    Resource.Drawable.ic_dashboard, Resource.Drawable.ic_headset, Resource.Drawable.ic_dashboard
        //};

        List<string> gridviewstring = new List<string>();
        List<int> imgview = new List<int>();

        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your fragment here
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // Use this to return your custom view for this Fragment
            // return inflater.Inflate(Resource.Layout.YourFragment, container, false);

            View view = inflater.Inflate(Resource.Layout.fragment_layout, container, false);

            conn.ConnectionString = query;

            // 
            MySqlCommand cmd = new MySqlCommand("Select * from wp_kdskli23jkposts where ID in (1,2,4)", conn);

            try
            {
                conn.Open();
                MySqlDataReader reader = cmd.ExecuteReader();

                //Read, get and loop the data value from the database
                while (reader.Read())
                {
                    string asd = reader["ID"].ToString();

                    gridviewstring.Add(asd);
                }
            }
            catch(MySqlException ex)
            {
                Android.Support.V7.App.AlertDialog.Builder except = new Android.Support.V7.App.AlertDialog.Builder(Activity);
                except.SetTitle("Please report this to our website(error server timeout)");
                except.SetMessage(ex.ToString());
                except.SetPositiveButton("Ok", (senderAlert, args) =>
                {
                    except.Dispose();
                });
                except.Show();
            }
            finally
            {
                conn.Close();
            }
            //gridviewstring.Add("location");
            //gridviewstring.Add("music");
            //gridviewstring.Add("book");

            imgview.Add(Resource.Drawable.ic_dashboard);
            imgview.Add(Resource.Drawable.ic_headset);
            imgview.Add(Resource.Drawable.ic_dashboard);

            string[] GridViewStringArray = gridviewstring.ToArray();
            int[] GridImgViewArray = imgview.ToArray();

            CustomGridViewAdapter adapter = new CustomGridViewAdapter(Activity, GridViewStringArray, GridImgViewArray);
            gridview = view.FindViewById<GridView>(Resource.Id.grid_view_image_text);
            gridview.Adapter = adapter;
            return view;
        }

    }
}
dy1byipe

dy1byipe1#

我编辑了适配器代码以使用字符串列表

namespace testing_code
{
    public class CustomGridViewAdapter : BaseAdapter
    {
        private Context context;
        private List<string> gridViewString;
        private List<string> gridViewImage;
        public CustomGridViewAdapter(Context context, List<string> gridViewstr, List<string> gridViewImage)
        {
            this.context = context;
            gridViewString = gridViewstr;
            this.gridViewImage = gridViewImage;
        }
        public override int Count
        {
            get
            {
                return gridViewString.Count;
            }
        }

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

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

        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            View view;
            LayoutInflater inflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService);
            if (convertView == null)
            {
                view = new View(context);
                view = inflater.Inflate(Resource.Layout.gridview_layout, null);
                TextView txtview = view.FindViewById<TextView>(Resource.Id.textViewGrid);
                ImageView imgview = view.FindViewById<ImageView>(Resource.Id.imageViewGrid);

                txtview.Text = gridViewString[position];
                imgview.SetImageBitmap(GetImageBitmapFromUrl(gridViewImage[position]));
            }
            else
            {
                view = (View)convertView;
            }
            return view;
        }

        private Android.Graphics.Bitmap GetImageBitmapFromUrl(string url)
        {
            Android.Graphics.Bitmap imageBitmap = null;

            using (var webClient = new System.Net.WebClient())
            {
                var imageBytes = webClient.DownloadData(url);
                if (imageBytes != null && imageBytes.Length > 0)
                {
                    imageBitmap = Android.Graphics.BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
               }

            }

            return imageBitmap;
        }
    }
}

然后您的片段使用url字符串列表

public class Fragment1 : SupportFragment
{
    MySqlConnection conn = new MySqlConnection();

    string query = "server=localhost;port=3306;database=dbsample;user id=root;password=123";

    GridView gridview;

    List<string> gridviewstring = new List<string>();
    List<string> imgview = new List<string>();

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Create your fragment here
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {

        View view = inflater.Inflate(Resource.Layout.fragment_layout, container, false);

        conn.ConnectionString = query;

        // 
        MySqlCommand cmd = new MySqlCommand("Select * from wp_kdskli23jkposts where ID in (1,2,4)", conn);

        try
        {
            conn.Open();
            MySqlDataReader reader = cmd.ExecuteReader();

            //Read, get and loop the data value from the database
            while (reader.Read())
            {
                string asd = reader["ID"].ToString();

                gridviewstring.Add(asd);
            }
        }
        catch (MySqlException ex)
        {
            Android.Support.V7.App.AlertDialog.Builder except = new Android.Support.V7.App.AlertDialog.Builder(Activity);
            except.SetTitle("Please report this to our website(error server timeout)");
            except.SetMessage(ex.ToString());
            except.SetPositiveButton("Ok", (senderAlert, args) =>
            {
                except.Dispose();
            });
            except.Show();
        }
        finally
        {
            conn.Close();
        }

        imgview.Add(" https://www.bellanaija.com/wp-content/uploads/2013/11/Remy-Martins-Pacesetters-VIP-Party-BellaNaija-November2013023-600x398.jpg");
        imgview.Add("http://www.allevents.ng/media/2018/at-the-club-with-remy-martins.png?width=375&mode=crop");

        imgview.Add("https://i.ytimg.com/vi/iLZz9Becq98/maxresdefault.jpg");

        CustomGridViewAdapter adapter = new CustomGridViewAdapter(Activity, gridviewstring, imgview);
        gridview = view.FindViewById<GridView>(Resource.Id.grid_view_image_text);
        gridview.Adapter = adapter;
        return view;
    }

}
}

希望这有帮助

相关问题