My Blog List

Wednesday 22 February 2012

How to add text to the ListView in Android


Hello frineds
This post will help you  to  add items to the Listview in android

Here is the output


Android comes with ListView Widget
There is two way to add item(String) to the list view
1st:
 Add String Array resource  in string.xml
Here is my string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World, ListviewExampleActivity!</string>
    <string name="app_name">ListviewExample</string>
    <string-array name="ListItem">
        <item >Red</item>
        <item >Green</item>
        <item >Blue</item>
        <item >Yellow</item>
        <item >Cyan</item>
       
    </string-array>

</resources>



Now add  android:entries=”@array/ListItem” to the ListView Widget
Here is my main.xml file

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

  

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:entries="@array/ListItem">
    </ListView>

</LinearLayout>


2nd way

Create ArrayAdapter  having String Array resource and set it to the Listview
Here is my ListView.java Activity

package com.bp.listview;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListviewExampleActivity extends Activity {
ListView l;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       String  arr[]={"Red","Green","Blue","Yellow","Cyan"};
      l=(ListView) findViewById(R.id.listView1);
  ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, arr);
  l.setAdapter(adapter);
  
        
    }
}

enjoy coding
for any query feel free to write @ bpsingh216@gmail.com
comment if it is usefull..