Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding grid items in grid view

How can I dynamically add grid items in grid view? Currently, I have an adapter containing my images. I want to get my images from an URL and dynamically add them to my grid view.

like image 604
Vincent Avatar asked Nov 04 '22 22:11

Vincent


1 Answers

Create custom adapter for grid view. And set that custom adapter for gird view. Here is the xml code for grid item.

    <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>

and here is xml for main layout.

    <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>

and here is custom adapter class which extends from 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;
  }
  }

Hope this can help u.

like image 160
Hein Avatar answered Nov 15 '22 13:11

Hein