Jong
Jong

Reputation: 9115

How to horizontally center composite list view items inside the list view?

I have a list view displaying items from a custom adapter which extends ArrayAdapter. Each item is a custom layout with a RelativeLayout being the root view. Now, I want this RelativeLayout to be centered horizontally inside the list view, but I everything I tried seems to fail.

Here's my custom adapter getView method:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = mInflater.inflate(R.layout.screens_listview_row, parent, false);
    return row;
}

And here's the file screens_listview_row.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/root"
   .....
   android:layout_gravity="center_horizontal" >
</RelativeLayout>

At first, it seemed like my layout parameters in the RelativeLayout were completely ignored, and it really was the case because i used inflate(R.layout.screens_listview_row, null), what is a problem like this answer says.

So now the only thing ignored is the layout_gravity parameter. I also tried layout_marginLeft (Everything in this layout is in absolute sizes so I could center it myself by giving a left margin...) but Android ignored it too. What is the problem here?

Upvotes: 0

Views: 2179

Answers (2)

Mohsen fallahi
Mohsen fallahi

Reputation: 917

try to use gravity instead of layout_gravity (as i know gravity is for the content of layout)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/root"
   .....
   android:gravity="center_horizontal" >
</RelativeLayout>

Upvotes: 2

Jong
Jong

Reputation: 9115

I didn't find out how to control the position of the items inside the ListView, so instead I made the ListView width exactly as the items' width, then controlled its position (Which practically controls the items' position).

Upvotes: 0

Related Questions