Site icon ParallelCodes

Android ListView From ArrayAdapter

Android ListView From ArrayAdapter – With Android ListView control, we can display a simple list in our application. ListView is view group that displays a list of scrollable items which are insterted in list using Adapter that pulls data from array or database.
Adapter works as an intermediate between the datasource and the AdapterView layout where Adapter retrieves the data.

ArrayAdapter can be used as a datasource to our Android ListView control when our data is simple array.

Ex : 

String[] DaysOfWeek = new String[] { “Sunday”, “Monday”, “Tuesdayy”,
“Wednesday”, “Thursday”, “Friday”, “Saturday” };

Now, let’s use is array in our listview control.

Edit the activity_main.xml file as below.

res > layout > activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout 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:orientation="vertical" >

<ListView
 android:id="@+id/lstView"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:clickable="true"
 android:divider="#000"
 android:dividerHeight="1dp"
 android:listSelector="#006cd9" >
 </ListView>

</LinearLayout>

And java class MainActivity.java as below :

MainActivity.java:

package parallelcodes.simplewidget;

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.ListView;
 import android.widget.Toast;

public class MainActivity extends Activity {
 ListView listView;
 String[] DaysOfWeek = new String[] { "Sunday", "Monday", "Tuesdayy",
 "Wednesday", "Thursday", "Friday", "Saturday" };

@Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 listView = (ListView) findViewById(R.id.lstView);
 ArrayAdapter adapter = new ArrayAdapter<String>(this,
 android.R.layout.simple_list_item_1, DaysOfWeek);
 listView.setAdapter(adapter);
 listView.setOnItemClickListener(new OnItemClickListener() {

@Override
 public void onItemClick(AdapterView<?> parent, View view,
 int position, long id) {
 Toast.makeText(getApplicationContext(),
 listView.getItemAtPosition(position).toString(),
 Toast.LENGTH_SHORT).show();
 }
 });
 }

}

This will produce following design listview control at runtime :

Android ListView Control From ArrayAdapter

Android ListView From ArrayAdapter

Furthermore, Android ListView control can be filled directly from design fill using string-array, using SimpleCursorAdapter, with custom layout file, from database, can be used with Images.

Please also see : Android Beginners Tutorial.


Exit mobile version