Pages

Subscribe:

Friday, January 14, 2011

List View Sample

Here is a sample code to learn Android List View

Layout


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

<ListView android:id="@+id/myList" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
</ListView>

</LinearLayout>

Code

package com.list.view;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ListViewSample extends Activity {
private enum myPhones {Android, iPhone, BlacBerry};
private ListView lv;
private String myArray[] = {"Android", "iPhone", "Blackberry"};
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        lv = (ListView) findViewById(R.id.myList);
        lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, myArray));
        lv.setOnItemClickListener((OnItemClickListener) new clicker());
        
    }
    
    class clicker implements ListView.OnItemClickListener {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String msg = null;
if(arg2 == myPhones.Android.ordinal()) {
msg = "You selected ";
} else if (arg2 == myPhones.iPhone.ordinal()) {
msg = "You selected ";
} else if (arg2 == myPhones.BlacBerry.ordinal()) {
msg = "You selected ";
}
Toast.makeText(getBaseContext(), msg + myArray[arg2], Toast.LENGTH_LONG).show();
}
    
    }
}


0 comments:

Post a Comment