Showing posts with label ListView in Android. Show all posts
Showing posts with label ListView in Android. Show all posts

Thursday, January 3, 2013

ListView with CheckBox using ArrayAdatpter in Android


Happy New Year to you All Android Developer :)

Today I am going to create a small Android application for
showing Check Box  in List View using Array Adapter in Android,
So lets start it now..

Note : at the end of  this Tutorial , you can find zip source code of this example .

We will create very simple app to do this work
 -------------------------------------------
App Name: CheckBoxListArrayAdapter
Package Name: com.rdc.activity
Android SDK: Android SDK 2.2 / API 8
Default Activity Name: MainActivity.java
-------------------------------------------

MainActivity.java



package com.rdc.activity;

import java.util.ArrayList;
import java.util.Arrays;

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

import com.rdc.adapter.PlanetArrayAdapter;
import com.rdc.model.Planet;
import com.rdc.model.PlanetViewHolder;

public class MainActivity extends Activity {

 private ListView mainListView = null;
 private Planet[] planets = null;
 private ArrayAdapter<Planet> listAdapter = null;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  mainListView = (ListView) findViewById(R.id.mainListView);

  // When item is tapped, toggle checked properties of CheckBox and
  // Planet.
  mainListView
  .setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> parent, View item,
    int position, long id) {
   Planet planet = listAdapter.getItem(position);
   planet.toggleChecked();
   PlanetViewHolder viewHolder = (PlanetViewHolder) item
    .getTag();
   viewHolder.getCheckBox().setChecked(planet.isChecked());
   }
  });

  // Create and populate planets.
  planets = (Planet[]) getLastNonConfigurationInstance();
  if (planets == null) {
   planets = new Planet[] { new Planet("Mercury"),
     new Planet("Venus"), new Planet("Earth"),
     new Planet("Mars"), new Planet("Jupiter"),
     new Planet("Saturn"), new Planet("Uranus"),
     new Planet("Neptune"), new Planet("Ceres"),
     new Planet("Pluto"), new Planet("Haumea"),
     new Planet("Makemake"), new Planet("Eris") };
  }
  ArrayList<Planet> planetList = new ArrayList<Planet>();
  planetList.addAll(Arrays.asList(planets));

  // Set our custom array adapter as the ListView's adapter.
  listAdapter = new PlanetArrayAdapter(this, planetList);
  mainListView.setAdapter(listAdapter);
 }

 public Object onRetainNonConfigurationInstance() {
  return planets;
 }
}

PlanetArrayAdapter.java
package com.rdc.adapter;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import com.rdc.activity.R;
import com.rdc.model.Planet;
import com.rdc.model.PlanetViewHolder;

/** Custom adapter for displaying an array of Planet objects. */
public class PlanetArrayAdapter extends ArrayAdapter<Planet> {

 private LayoutInflater inflater;

 public PlanetArrayAdapter(Context context, List<Planet> planetList) {
 super(context, R.layout.simplerow, R.id.rowTextView, planetList);
 //Cache the LayoutInflate to avoid asking for a new one each time.
  inflater = LayoutInflater.from(context);
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent){
  Planet planet = (Planet) this.getItem(position);
  CheckBox checkBox;
  TextView textView;

  // Create a new row view
  if (convertView == null) {
  convertView = inflater.inflate(R.layout.simplerow, null);

  textView = (TextView) convertView.findViewById(R.id.rowTextView);
  checkBox = (CheckBox) convertView.findViewById(R.id.CheckBox01);

  convertView.setTag(new PlanetViewHolder(textView, checkBox));

  // If CheckBox is toggled, update the planet it is tagged with.
  checkBox.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
    CheckBox cb = (CheckBox) v;
    Planet planet = (Planet) cb.getTag();
    planet.setChecked(cb.isChecked());
   }
  });
  }
  // Re-use existing row view
  else {

  PlanetViewHolder viewHolder = (PlanetViewHolder) convertView
     .getTag();
   checkBox = viewHolder.getCheckBox();
   textView = viewHolder.getTextView();
  }

  checkBox.setTag(planet);

  // Display planet data
  checkBox.setChecked(planet.isChecked());
  textView.setText(planet.getName());

  return convertView;
 }

}


Planet.java
package com.rdc.model;

/** Holds planet data. */
public class Planet {
 private String name = "";
 private boolean checked = false;

 public Planet() {
 }

 public Planet(String name) {
  this.name = name;
 }

 public Planet(String name, boolean checked) {
  this.name = name;
  this.checked = checked;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public boolean isChecked() {
  return checked;
 }

 public void setChecked(boolean checked) {
  this.checked = checked;
 }

 public String toString() {
  return name;
 }

 public void toggleChecked() {
  checked = !checked;
 }
}

PlanetViewHolder.java
package com.rdc.model;

import android.widget.CheckBox;
import android.widget.TextView;

/** Holds child views for one row. */
public class PlanetViewHolder {
 private CheckBox checkBox;
 private TextView textView;

 public PlanetViewHolder() {
 }

 public PlanetViewHolder(TextView textView, CheckBox checkBox) {
  this.checkBox = checkBox;
  this.textView = textView;
 }

 public CheckBox getCheckBox() {
  return checkBox;
 }

 public void setCheckBox(CheckBox checkBox) {
  this.checkBox = checkBox;
 }

 public TextView getTextView() {
  return textView;
 }

 public void setTextView(TextView textView) {
  this.textView = textView;
 }
}


main.xml
<?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:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:id="@+id/mainListView">
 </ListView>

</LinearLayout>



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

 <TextView
  android:id="@+id/rowTextView"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:padding="10dp"
  android:textSize="16sp">
 </TextView>

 <CheckBox
  android:id="@+id/CheckBox01"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:padding="10dp"
  android:layout_alignParentRight="true"
  android:layout_marginRight="6sp"
  android:focusable="false">
 </CheckBox>

</RelativeLayout>



AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc.activity"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="8" />

 <application
  android:icon="@drawable/icon"
  android:label="@string/app_name">
  <activity
   android:name=".MainActivity"
   android:label="@string/app_name">
   <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>

 </application>
</manifest>

Here is the Result screen



You can download the complete source code zip file here : CheckBoxListArrayAdapter.zip

Thursday, August 18, 2011

ListView in Android (Advance)

We have already know how to show the list in Android see tutorial ListView in Android (Basic)


This tutorial describes how to use ListView and ListActivity in Android.
While we will create array list in a separate XML file.
also it will show the new page when you click on List Item.

Project Structure is look like this


okay! so let's try this small app 


 -------------------------------------------
App Name: ListViewBasic
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default ListActivity Name: ActivityListView
------------------------------------------- 

ActivityListView.java


package com.rdc;

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

public class ActivityGamesList extends Activity {

 private String[] gamelistArray;
 private String[] gameDetailsListArray;
 private ListView listGames = null;
 ArrayAdapter<String> adapter;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  listGames = (ListView) findViewById(R.id.listViewGame);
  gamelistArray = getResources().getStringArray(R.array.gameslist);
  gameDetailsListArray = getResources().getStringArray(
    R.array.gamesDetails);

  adapter = new ArrayAdapter<String>(this,
    android.R.layout.simple_list_item_1, android.R.id.text1,
    gamelistArray);

  listGames.setAdapter(adapter);

  listGames.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {

    // Get the item that was clicked
    Object itemName = listGames.getItemAtPosition(position);
    String keyword = itemName.toString();
    String info = gameDetailsListArray[position];
    Toast.makeText(getApplicationContext(),
    "You have selected:  " + keyword, Toast.LENGTH_SHORT)
      .show();
    Intent i = new Intent(getBaseContext(),
      ActivityGameDetails.class);
    i.putExtra("info", info);
    i.putExtra("name", keyword);
    startActivity(i);

   }
  });
 }
}


ActivityGameDetails.java
package com.rdc;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ActivityGameDetails extends Activity {

 private TextView txtTitle = null;
 private TextView txtDetails = null;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.game_details);
  Bundle bundle = new Bundle();
  String info = getIntent().getStringExtra("info");
  txtTitle = (TextView) findViewById(R.id.textView1);
  txtTitle.setText(info);
  String name = getIntent().getStringExtra("name");
  txtDetails = (TextView) findViewById(R.id.txtgamedetailsTitle);
  txtDetails.setText("Details of " + name);
 }
}


create these xml files in res/layout folder main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent">
 <ListView
  android:layout_height="wrap_content"
  android:layout_width="match_parent"
  android:id="@+id/listViewGame"></ListView>

</LinearLayout>

game_details.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:weightSum="1">
 <TextView
  android:text="TextView"
  android:layout_height="wrap_content"
  android:layout_width="match_parent"
  android:layout_weight="0.30"
  android:gravity="center"
  android:textSize="20sp"
  android:id="@+id/txtgamedetailsTitle"></TextView>
 <ScrollView
  android:id="@+id/layscroll"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_weight="0.70">
  <TextView
   android:id="@+id/textView1"
   android:text="@string/gameDetails"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"></TextView>
 </ScrollView>

</LinearLayout>


create these below xml files in res/values folder arraylist_games.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
       <string-array name="gameslist">
        <item>Soccer</item>
        <item>Cricket</item>
        <item>Chess</item>
        <item>WWE</item>
        <item>NFS Most Wanted</item>
        <item>Counter Strike</item>
        <item>Angry Birds</item>
        <item>Lord of the Rings</item>
        <item>Mario</item>
        <item>Prince of Persia</item>
        <item>Resident Evil</item>
        <item>Far Cry</item>
        <item>Minesweeper</item>
        <item>Jumper</item>      
        
    </string-array>
       
    
    <string-array name="gamesDetails">
        <item>Association football, more commonly known as football or soccer, is a sport played between two teams of eleven players with a spherical ball. At the turn of the 21st century, the game was played by over 250 million players in over 200 countries, making it the world\'s most popular sport..</item>
        <item>Cricket is a bat-and-ball game played between two teams of 11 players on a field, at the centre of which is a rectangular 22-yard long pitch</item>
        <item>Chess is a two-player board game played on a chessboard, a square checkered board with 64 squares arranged in an eight-by-eight grid.</item>
        <item> WWE is an American publicly traded, privately controlled entertainment company dealing primarily in professional wrestling which despite being scripted and not real are very popular, with major revenue sources also coming from film, music, product licensing, and direct product sales.</item>
        <item>Need for Speed: Most Wanted is an upcoming 2012 racing video game, developed by British games developer Criterion Games and published by Electronic Arts. Announced on 4 June 2012, during EA\'s E3 press conference, Most Wanted is the nineteenth title in the long-running Need for Speed series and second game in the Most Wanted series.</item>
        <item>The game was the most played Half-Life modification in terms of players, according to GameSpy in 2008.</item>
        <item>Angry Birds is a strategy puzzle video game developed by Finnish computer game developer Rovio Mobile. Inspired primarily by a sketch of stylized wingless birds, the game was first released for Apple\'s iOS in December 2009.</item>
        <item>The Lord of the Rings is an epic film trilogy consisting of three fantasy adventure films, directed by Peter Jackson, based on the three-volume book of the same name by English author J. R. R. Tolkien.</item>
        <item>Mario is a fictional character in the Mario video game franchise by Nintendo, created by Japanese video game designer Shigeru Miyamoto. Serving as Nintendo\'s mascot and the eponymous protagonist of the series, Mario has appeared in over 200 video games since his creation.</item>
        <item>Prince of Persia is a video game franchise created by Jordan Mechner, originally developed for and released on the Apple II Computer in 1989. The original game and its first sequel were 2D platform games, but the series made the switch to three-dimensional following the release of Prince of Persia 3D in 1999.</item>
        <item>Resident Evil, originally released as Bio Hazardin Japan, is a survival horror video game by Capcom. The first installment in the Resident Evil series was originally released in 1996 for the PlayStation and was soon ported to the Sega Saturn and PC, as well as the Nintendo DS some years later.</item>
        <item>Far Cry is first-person shooter video game developed by Crytek Studios and published by Ubisoft on March 23, 2004, for Microsoft Windows. Far Cry sold 730,000 units within four months of release.It received positive reviews upon release. The original game has since spawned a series of sequels and spin-off games and a movie.</item>
        <item>Minesweeper is a single-player video game. The object of the game is to clear an abstract minefield without detonating a mine. </item>
        <item>City Jumper : You can leap over buildings in a single bound, but scrape your back on the Golden Gate bridge and you will be cut in half.</item>
        
    </string-array>    
</resources>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="10" />

 <application
  android:icon="@drawable/icon"
  android:label="@string/app_name">
  <activity
   android:name=".ActivityGamesList"
   android:label="Games List">
   <intent-filter>
   <action android:name="android.intent.action.MAIN" />
   <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>

  <activity
   android:name=".ActivityGameDetails"
   android:label="Game Details">
   <intent-filter>
   <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>

 </application>
</manifest>

The output Screen will be like this..
                                   
                                                                Games Name List

When you select any one it will show the Game Details like this..



You can download the complete source code zip file here : ListViewAdvance

 cheers!!

 I'd love to hear your thoughts!

Wednesday, August 10, 2011

ListView in Android (Basic)

ListView: ListView is a view group that displays a list of scrollable items. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array and converts each item result into a view that's placed into the list.

This tutorial describes how to use ListView and ListActivity in Android.

okay! so let's try this small app


 -------------------------------------------
App Name: ListViewBasic
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default ListActivity Name: ActivityListView
-------------------------------------------


ActivityListView.java






package com.rdc;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ActivityListView extends ListActivity {

 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);

 // Create an array of Strings, that will be put to our ListActivity
 String[] namesArray = new String[] { "Linux", "Windows7", "Eclipse",
    "Suse", "Ubuntu", "Solaris", "Android", "iPhone" };
 
 /* Create an ArrayAdapter, that will actually make the Strings above
  appear in the ListView */
 this.setListAdapter(new ArrayAdapter<String>(this,
   android.R.layout.simple_list_item_1, namesArray));
 }

  @Override
  protected void onListItemClick(ListView l, View v, 
  int position, long id) {
 super.onListItemClick(l, v, position, id);
 
 // Get the item that was clicked
 Object o = this.getListAdapter().getItem(position);
 String keyword = o.toString();
 Toast.makeText(this, "You selected: " + keyword, 
   Toast.LENGTH_SHORT).show();
 }
}

main.xml
<?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">
 <TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/hello" />
</LinearLayout>


AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="10" />

 <application
  android:icon="@drawable/icon"
  android:label="@string/app_name">
  <activity
   android:name=".ActivityListView"
   android:label="@string/app_name">
   <intent-filter>
   <action android:name="android.intent.action.MAIN" />
   <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>

 </application>
</manifest>

The output Screen will be like this..


You can download the complete source code zip file here : ListViewBasic 

 cheers!!

 I'd love to hear your thoughts!