1

As you can see from the screenshot below, the first item in the listview isnt centered vertically. How can I center it?

screenshot

Activity XML

 <ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/listView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_above="@+id/button"
    android:layout_alignParentTop="true" />

Code, I'm just populating the listview from books array...

List<String> books = new ArrayList<String>();
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(Main.this,  android.R.layout.simple_list_item_1, books);
lvFirst.setAdapter(adapter1);
Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
luk492
  • 350
  • 3
  • 15
  • 1
    Read about custom adapter - http://stackoverflow.com/questions/8166497/custom-adapter-for-list-view – Divers May 20 '15 at 20:23
  • I don't see any obvious reason. The only thing that comes to mind would be a line feed at the beginning of the string. Make sure you trim all your texts before adding them to the list. – njzk2 May 20 '15 at 22:16

2 Answers2

0

Try adding this line to your ListView XML:

android:gravity="center"

It should look like this:

<ListView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/listView"
  android:layout_alignParentLeft="true"
  android:layout_alignParentStart="true"
  android:layout_above="@+id/button"
  android:layout_alignParentTop="true" 
  android:gravity="center"/>

EDIT:

Sorry, now I understood your issue.

You're using "android.R.layout.simple_list_item_1" as your built in layout, but it won't work that way.

This is a duplicate of this question.

Just summing it up, you need to create your own layout to pass to the adapter. The answer is in the question link posted above.

Community
  • 1
  • 1
  • Tried it, cant add gravity to listview – luk492 May 20 '15 at 20:52
  • `it won't work that way.` why not? I don't see any good reason to go into custom layouts just because one does not understand what is happening – njzk2 May 20 '15 at 22:17
  • The `android.R.layout.simple_list_item_1` is a built-in layout from the Android OS, and because of that, you can't change any of the contents inside. If you want to customize your items on the list beyond that, you can either create a custom layout, which won't take 5 minutes, or create a custom adapter, which will take a little bit more time. – Thyen Hong Guedes Chang May 21 '15 at 13:42
0

Thank you for your time and answers, but I couldnt believe that that it was that bad of an implementation so I just listed some default layouts and this fixed my issue, so I want to write it here to help someone in the future.

adapter1 = new ArrayAdapter<String>(Main.this, android.R.layout.simple_selectable_list_item, books);

I just changed:

android.R.layout.simple_list_item_1

to:

android.R.layout.simple_selectable_list_item
luk492
  • 350
  • 3
  • 15