Berkenoski
Berkenoski

Reputation: 21

How to offset row margins of a GridView

I have a gridview full of images and the rows of a grid view align by columns like this

1_2_3

4_5_6

7_8_9

However I want to offset certain rows to get something like this

1_2_3_

_4_5_6

7_8_9_

So that the second row and an unknown number of additional rows are moved over to the right.

One solution is to make multiple gridviews and shift them over accordingly but that won't work when I have alot of rows. Another would be to somehow change the margins in the ImageAdapter using the position to get the row but I haven't been able to make that work without crashing. Is trying to edit the LayoutParams in the ImageAdapter even the right way to go about something like this?

Upvotes: 2

Views: 2101

Answers (1)

lucian
lucian

Reputation: 537

You can use two types of views, with two layouts, for example:

in your adapter, you could implements:

@Override
public int getViewTypeCount() {
  return 2;
}

@Override
public int getItemViewType(int position) {
 if (isImageLeft(position)) {
  return VIEW_TYPE_LEFT_IMAGE; //TODO: you should define it 
} else {
  return VIEW_TYPE_RIGHT_IMAGE;//TODO: you should define it
}    

@Override
public View getView(int position, View convertView, ViewGroup parent) {
  View view = convertView;
  if (view == null){
    if (getItemViewType(int position) == VIEW_TYPE_LEFT_IMAGE){
      view = inflater.inflate(R.layout.layout_image_left, null);//TODO: you should have set the reference of LayoutInflater
    }else{
      view = inflater.inflate(R.layout.layout_image_right, null);
    }    
  } 
  //.......
}

and in those two layout file, you could set a LinearLayout (or other layout as you like), with ImageView inside with the left, or right margin respectively. for example:

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

  <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginLeft="50dp" />
</LinearLayout>

Upvotes: 2

Related Questions