Sunday 28 July 2013

List in Android using ListActivity Class

Leave a Comment

List View is one of the group in android, that displays a list of scrollable items. The display of elements in a lists is a very common pattern in mobile applications. The user sees a list of items and can scroll through them. An Adapter is used to list the elements in scrollable manner, which in turn gets the data from the source such as an array or from the database and convert each elements into a view of list.
Some of the commonly used  Adapter are :-
Lets Begin with Coding, to make a list I am using ListActivity Class instead of extending Activity Class.
Step 1:- Set up your project and create the main xml file, my is activity_list.xml
<TextView 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:textSize="25dp"
    android:padding="5dp">
    </TextView>
Step 2:-  In your java file,
package com.arpit.simplelistdemo;
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;
// I am using ListActivity class instead of Activity
public class ListActivity extends android.app.ListActivity implements OnItemClickListener {
// create the array, this is going to be displayed in a list
  String[] Language = { "JAVA", "JAVASCRIPT", "JQUERY", "JQUERYMOBILE", "C",    
            "ANDRIOD", "PHONEGAP", "DATA STRUCTURE", "WINDOWS", ".NET", "AJAX",
            "C++", "SQL", "HTML5", "CSS3" };
    ListView list;                       
    ArrayAdapter<String> adapter;   // set up an adapter
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
// set up an instance of adapter and passing array and layout to it      
adapter = new ArrayAdapter<String>(this, R.layout.activity_list,
                Language);
        setListAdapter(adapter);
       
        list = getListView();
        list.setOnItemClickListener(this); // click listener on tap of element on list       
    }
    public void onItemClick(AdapterView<?> adapter, View arg1, int position, long arg3) {
       
        String str = adapter.getItemAtPosition(position).toString();
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
       
    }
}

0 comments:

Post a Comment