Android : How to create a Basic List View

Points To Remember

  • You need to create a ListView in your activity.
  • Then create a view for Item of the ListView.
  • Create an Adapter and a list of objects to display.
  • Pass the List of objects to the ListView.

How to create a Basic List View 


Your Activity may look like the following activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="Planet List"
        android:textAlignment="center"
        android:textSize="24dp"
        />
    <ListView
        android:id="@+id/list_view_drawer"
        android:layout_marginTop="50dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:dividerHeight="1dp"
        android:divider="@android:color/holo_blue_light"
        xmlns:android="http://schemas.android.com/apk/res/android" />


</RelativeLayout>

Your item may look like the following list_view_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView
    android:layout_height="50dp"
    android:textAlignment="gravity"
    android:textColor="@android:color/holo_blue_dark"
    android:paddingLeft="15dp"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:gravity="center_vertical"
    android:layout_width="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android" />

Your activity may look like the following

package com.ekiras.demo;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.ekiras.app2.fragment.BuzzListFragment;

public class MainActivity extends ActionBarActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        String [] planets = new String[]{
          "Mercury","Mars","Earth","Jupitor","Mars","Venus","Pluto"
        };

        ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.list_view_item, planets);

        ListView listView = (ListView) findViewById(R.id.list_view_drawer);
        listView.setAdapter(adapter);
    }

}

Your Application will look as shown in the image



Leave a Comment

Powered by Blogger.