Set string array to listview in android programmatically

Add string array[] items into listview programmatically.

Using string array developer can define list items directly through MainActivity.java file with the use of String array variable. So here is the complete step by step tutorial for Set string array to listview in android.

android-project-download-code-button

How to Set string array to listview in android.

Code for MainActivity.java file.

 package com.android_examples.com.listviewsimple;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

 ListView listView;
 
 // Define string array.
 String[] listValue = new String[] {"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT"};
 
 @Override
 protected void onCreate(Bundle savedInstanceState) 
 {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 listView = (ListView)findViewById(R.id.listView1);
 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_2, android.R.id.text1, listValue);
 
 listView.setAdapter(adapter); 
 
 
 
 }
}

Code for activity_main.xml layout file.

 <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:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.android_examples.com.listviewsimple.MainActivity" >

 <ListView
 android:id="@+id/listView1"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_alignParentTop="true"
 android:layout_centerHorizontal="true"
 
 >
 </ListView>

</RelativeLayout>

Screenshot:

Set string array to listview in android

Click Here To Download Set string array to listview in android Project.

2 Comments

  1. How can I create the string array programmatically? I mean for example, can I add to the string array, the items, “ONE”,”TWO”,”THREE”,.. programmatically?

Leave a Reply

Your email address will not be published. Required fields are marked *