How set Alternate Cell Color in a Grid

后端 未结 2 1188
野性不改
野性不改 2021-01-22 02:23

How set alternate cell Color in a grid ? I\'ve found a lot of questions/tutorials about how to set row colors but nothing about cells\' color. Thanks in advance

相关标签:
2条回答
  • 2021-01-22 02:54

    A step forward and it works

    public class ListViewA extends Activity {
    GridView MyGrid;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        MyGrid = (GridView) findViewById(R.id.gridview);
        MyGrid.setAdapter(new ImageAdapter(this));
    }
    
    public class ImageAdapter extends BaseAdapter {
        Context MyContext;
    
        public ImageAdapter(Context _MyContext) {
            MyContext = _MyContext;
        }
    
        @Override
        public int getCount() {
            return 9;
        }
    
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
    
            if (convertView == null) {
    
                LayoutInflater li = getLayoutInflater();
                view = li.inflate(R.layout.main, null);
            }
    
            if (position % 2 == 0)
                view.setBackgroundColor(0x30FF0000);
            else
                view.setBackgroundColor(0x300000FF);
            return view;
    
        }
    
        @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;
        }
    }
    

    }

    0 讨论(0)
  • 2021-01-22 03:06

    If you got a lot of examples for listView, why not just use getView method, as getView method is used for adapter and adapter is used in both views, list and grid. just set background of view according to the position of view in adapterview.

    protected void getView(AdapterView<> adapterView, View convertView, int position, long id)
    {
    
        LayoutInflater inflater = (LayoutInflater)context.getSystemService
          (Context.LAYOUT_INFLATER_SERVICE);
        View view =inflater.inflate(yourlayout.xml, null);
    
        if(position%2==0)
            view.setBackgroundColor(color1);
        else
            view.setBackgroundColor(color2);
         return view;
    }
    
    0 讨论(0)
提交回复
热议问题