在网格视图中动态添加网格项

Vin*_*ent 5 android gridview

如何在网格视图中动态添加网格项?目前,我有一个包含我的图像的适配器.我想从URL获取图像并将其动态添加到网格视图中.

Hei*_*ein 2

为网格视图创建自定义适配器。并为网格视图设置自定义适配器。这是网格项的 xml 代码。

    <linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:id="@+id/GridItem"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content">

       <imageview android:id="@+id/grid_item_image"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content">
       </imageview>
    </linearlayout>
Run Code Online (Sandbox Code Playgroud)

这是主要布局的 xml。

    <gridview xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/GridView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    </gridview>
Run Code Online (Sandbox Code Playgroud)

这是从 BaseAdapter 扩展的自定义适配器类

    public class ImageAdapter extends BaseAdapter
    {
    Context context;

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

  @Override
  public int getCount() 
  {
     //return numbers of element u want on the grid
     return 9;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) 
  {
     View v = convertView;

     if ( convertView == null )
     {
        //here we inflat the layout
        LayoutInflater li = getLayoutInflater();
        v = li.inflate(R.layout.grid_item, null);

        //here add the image      
        ImageView iv = (ImageView)v.findViewById(R.id.grid_item_image);
        iv.setImageResource(R.drawable.icon);
     }

     return v;
  }

  @Override
  public Object getItem(int arg0) {
     // TODO Auto-generated method stub
     return null;
  }

  @Override
  public long getItemId(int arg0) {
     // TODO Auto-generated method stub
     return 0;
  }
  }
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助你。