Create listview in android programmatically

Dynamically make listview with custom list items using MainActivity.java coding file without layout xml.

Creating listView using coding file is very easy and mostly used to build large scale android apps because dynamically app developer can modify their develop app directly through MainActivity.java programming file. So here is the complete step by step tutorial for Create listview in android programmatically.

android-project-download-code-button

How to Create listview in android programmatically.

Code for MainActivity.java file.

 package com.createlistviewprogrammatically_android_examples.com;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 LinearLayout linearLayout = new LinearLayout(this);
 
 ListView DynamicListView = new ListView(this);
 
 final String[] DynamicListElements = new String[] {
 "Android",
 "PHP",
 "Android Studio",
 "PhpMyAdmin"
 };
 
 ArrayAdapter<String> adapter = new ArrayAdapter<String>
 (MainActivity.this, android.R.layout.simple_list_item_1, DynamicListElements);

 DynamicListView.setAdapter(adapter);
 
 linearLayout.addView(DynamicListView);
 
 this.setContentView(linearLayout, new LinearLayout.LayoutParams(
 LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
 
 DynamicListView.setOnItemClickListener(new OnItemClickListener() {

 @Override
 public void onItemClick(AdapterView<?> parent, View view,
 int position, long id) {
 // TODO Auto-generated method stub
 
 Toast.makeText(MainActivity.this, DynamicListElements[position], Toast.LENGTH_SHORT).show();
 }
 
 
 });
 
 }
}

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.createlistviewprogrammatically_android_examples.com.MainActivity" >

 
</RelativeLayout>

Screenshot:

Create listview in android programmatically

Click here to download Create listview in android programmatically project.

Leave a Reply

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