Friday, October 14, 2016

Android Simple Listview Example

In Android ListView is a class to show a list of items that can be scrolled.

To make a ListView is very easy in android. Follow these steps :

1. make an activity layout that contains a ListView. make a layout xml file with name activity_listview.xml like in the example below :

<?xml version="1.0" encoding="utf-8"?>
<ListView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</ListView>
2. make a java activity class with name ListViewActivity.java


package com.example.myapplication;

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

import java.util.ArrayList;

/**
 * Created by SONY on 14/10/2016.
 */
public class ListViewActivity extends Activity {

    private ListView listView;
    private ArrayAdapter<String> adapter;
    private ArrayList<String> data = new ArrayList<String>();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listview);
        listView = (ListView) findViewById(R.id.listView);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data );
        listView.setAdapter(adapter);
        populateListView();
    }
    private void populateListView() {
        data.add("One");
        data.add("Two");
        data.add("Three");
        data.add("Four");
        data.add("Five");
        data.add("Six");
        data.add("Seven");
        data.add("Eight");
        data.add("Nine");
        data.add("Ten");
        data.add("eleven");
        data.add("Twelve");
        adapter.notifyDataSetChanged();}
}
3. edit AndroidManifest.xml like this :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ListViewActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>



4. Now it is ready to run your application and see result like this picture:

simple listview example




Thank you for visiting our website. Just comment below if you have any question to ask.

No comments:

Post a Comment