Pages

Friday, June 5, 2015

A Simple Android ListView Example



This tutorial demonstrates ,How to Display Some text in a ListView 

 1.Open Android Studio /Eclipse and create a
new Android project.

 2.Go to our res/layout/activity_my.xml in Android Studio or res/layout/activity_main.xml in Eclipse and create our Main Activity Layout 


  •  The layout has One ListView to display List of items



<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"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MyActivity">
 
    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@android:id/list"       
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true" />
 
</RelativeLayout>

3.Then in our MyActivity.java file we :
  • Change the MyActivity  class to extend  from ListActivity
  • Define an Array Called yourArray  and Initialize 
  • Define a new ArrayAdapter
    • First parameter - Context
    • Second parameter - Layout for the row
    • Third parameter -the Array of data
  •   setListAdapter( ) - Bind the ArrayAdapter to the ListActivity  



package com.example.morningsun.myapplication;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;


public class MyActivity extends ListActivity {

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

        String[] yourArray ={"ABC","ZXC","ASD"};
        setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, yourArray ));


    }

}

No comments:

Post a Comment