Monday, 7 October 2013

Android ListView Tutorial


Complete Android Tutorial

Developed using Android SDK API 18 

This tutorial will help you how to use list view in your android application.

File: activity_main.xml


<?xml version="1.0" encoding="utf-8"?>

    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#6B8E23"
        android:paddingBottom="2dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingTop="2dp"
        android:text="@string/textview"
        android:textColor="#FFFFFF"
        android:textSize="25sp" />
File: MainActivity.java


package com.mavenscientists.listview;

import android.os.Bundle;
import android.app.ListActivity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends ListActivity
{

 static final String[] BRANDS = new String[] {
  "Apple", "Google", "Microsoft", "Maven Scientists", "Nokia", "Motorolla", "Micromax", 
  "LG", "Sony", "Intel", "Adobe", "LinkedIn", "Facebook", "Instagram", 
  "Oracle", "Twitter", "Thomson Reuters"  };
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  
  //setContentView(R.layout.activity_main);
  setListAdapter(new ArrayAdapter<String>(this, R.layout.activity_main,BRANDS));
   
  ListView listView = getListView();
  listView.setTextFilterEnabled(true);
  
  // code to perform when the item in list view is clicked
  listView.setOnItemClickListener(new OnItemClickListener() {
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {
       Toast.makeText(getApplicationContext(),
    ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
   }
  });
  
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

}
Final Snapshot


List View in android - Maven Scientists
List View in android

Note: the background color, text size and Padding properties are defined in the activity_main.xml and can be changed as per your need.


Liked this tutorial

Please Share and Follow us on Facebook : http://facebook.com/MavenScientists


References

For More information you can visit the official android developer website: http://developer.android.com/guide/topics/ui/layout/listview.html

Get Ebooks delivered to your email id

Comments

Subscribe to our channel

Facebook

Powered by Blogger.

Home | Contact Us | DMCA | Terms of Service | Privacy | Advertise

Maven Scientists