Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

android - Dynamic Grid Layout

I want to implement grid, which will be populated dynamically. I want to know what is the best approach to implement this Relative layout(List View) or Grid Layout?

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can generate a GridView dynamically.

GridView would contain of ImageView and TextView as per your need. You will have to use your custom adapter. In it's getView method, populate the ImageView and TextView.

Example:

GridView item.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imgItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/txtItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:fontFamily="trebuchet"
        android:textColor="@android:color/black"
        android:textSize="15sp"
        android:textStyle="bold" />

</LinearLayout>

Java code:

A POJO class for item:

public class Item
{
    String title;
    Drawable image;
    //getter setter
}

Adapter class:

//getView method in your adapter class

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    View itemView = convertView;
    ViewHolder holder = null;

    if (itemView == null)
    {
        final LayoutInflater layoutInflater =
            (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        itemView = layoutInflater.inflate(resourceId, parent, false);

        holder = new ViewHolder();
        holder.imgItem = (ImageView) itemView.findViewById(R.id.imgItem);
        holder.txtItem = (TextView) itemView.findViewById(R.id.txtItem);
        itemView.setTag(holder);
    }
    else
    {
        holder = (ViewHolder) itemView.getTag();
    }

    Item item = getItem(position);
    holder.imgItem.setImageDrawable(item.getImage());
    holder.txtItem.setText(item.getTitle());

    return itemView;
}

Now add adapter data in your Activity class and then set that adapter to GridView.

Refer to this and this

Hope it helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...