android grid layout code example

Example 1: android grid column

in res/values/dimens.xml:

<integer name="grid_columns">1</integer>

in res/values-w600dp/dimens.xml:

<integer name="grid_columns">2</integer>

in java:

int gridColumns = getResources().getInteger(R.integer.grid_columns);

Example 2: how to change background color of grid in grid layout in android

new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, student_array) {
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);

    int color = 0x00FFFFFF; // Transparent
    if (someCondition) {
      color = 0xFF0000FF; // Opaque Blue
    }

    view.setBackgroundColor(color);

    return view;
  }
};

Tags:

Java Example