How to set Alternate Row Color in a Gridview Android?

后端 未结 2 2022
迷失自我
迷失自我 2021-01-06 07:12

How to set alternate row color in a gridview? I have searched a lot of tutorial about how to set grid view row colors,but nothing about gridview row color. I got list view w

相关标签:
2条回答
  • 2021-01-06 07:27

    Create a custom adapter and override its getView method:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        gridView = (GridView) findViewById(R.id.gridview1);
    
        MyAdapter adapter = new MyAdapter(this,
                R.layout.item, numbers);
    
        gridView.setAdapter(adapter);
    
    }
    
    public class MyAdapter extends ArrayAdapter<String> {
    
        String[] objects;
        Context context;
    
        public MyAdapter(Context context, int textViewResourceId, String[] objects) {
            super(context, textViewResourceId, objects);
            this.context = context;
            this.objects = objects;
        }
    
    
        @Override
        public View getView(int position, android.view.View convertView, android.view.ViewGroup parent) {
            TextView tv;
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                tv = (TextView)inflater.inflate(R.layout.item,parent,false);
            } else {
                tv = (TextView) convertView;
            }
            tv.setText(objects[position]);
            if (position % 2 == 0)
                tv.setBackgroundColor(Color.BLACK);
            else
                tv.setBackgroundColor(Color.WHITE);
    
            return tv;
        }
    }
    

    item.xml

    <?xml version="1.0" encoding="utf-8"?>
    
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent">
    
    </TextView>
    
    0 讨论(0)
  • 2021-01-06 07:43

    Use custom Adaptor and in Custom adaptor
    you will be having method getView

    Use this code in your getView Method

    if(position % ( 2*columnCount ) == 0)
    {
    // set first color 
    }
    else 
    {
     // set alternate row's  color
    }
    
    0 讨论(0)
提交回复
热议问题