Abhilash Harsole
Abhilash Harsole

Reputation: 254

How to apply different colors for gridview row items in android?

I have a grid view with two columns. I want to set different colors for the grid view row items. For example, I want 4 colors to be applied after every 4th row item, alternately.

android:background="@color/dividerColor"/>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1.6"
    android:padding="8dp">
    <GridView
        android:id="@+id/gridCategory"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="2"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:stretchMode="columnWidth"
        android:gravity="center">
    </GridView>
</LinearLayout>

Upvotes: 1

Views: 2657

Answers (1)

lanniaoyidingying
lanniaoyidingying

Reputation: 101

this may helps ,have a try.

class MyListAdapter extends BaseAdapter{

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public News getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView==null){
            convertView=View.inflate(mActivity, R.layout.gridview, null);
            TextView tvContent = (TextView) convertView
                    .findViewById(R.id.iv_pic);
        }
        TextView info = getItem(position);
        info.setText(info.title);
        //Is to ensure that the two columns
        int type=position/2;
        //For each row processing respectively
        switch(type){
            case 0:
                convertView.setBackgroundColor(Color.parseColor("#ff0000")); 
                break;
            case 1:
                convertView.setBackgroundColor(Color.parseColor("#00ff00"));
                break;
            case 2:
                convertView.setBackgroundColor(Color.parseColor("#0000ff"));
                break;
            case 3:
                convertView.setBackgroundColor(Color.parseColor("#000000"));
                break;
        }
        return convertView;
    }

}

Upvotes: 3

Related Questions