In the article titled “Event Listener for Checkboxes in ListView“, we have seen how to add checkboxes to a listview for selecting multiple items at a time. In this article we will see how to add ToggleButtons to listview for enabling multi selection mode in the listview. We will make use custom layout for adding togglebuttons to listview.
This application is developed in Eclipse ( 4.2.0 ) with ADT plugin ( 20.0.3 ) and Android SDK ( R20.0.3 ) .
1. Create a new Android application project namely “ListViewToggleButton”
2. Design application launcher icon
3. Create a blank activity to define MainActivity class
4. Enter MainActivity details
5. Delete the Android’s Support library from this project, if exists
By default Eclipse ( 4.2.0) adds Android Support Library to Android application project. For this application, we don’t need to use this support library. So the library file libs/android-support-v4.jar may be removed manually via ProjectExplorer by simply right click on the file and then clicking the menu item “delete”.
6. Update the file res/values/strings.xml
<resources> <string name="app_name">ListViewToggleButton</string> <string name="hello_world">Hello world!</string> <string name="menu_settings">Settings</string> <string name="title_activity_main">ListView With ToggleButton</string> </resources>
7. Update the layout file res/layout/activity_main.xml
<RelativeLayout 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" > <ListView android:id="@+id/lv_countries" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" tools:context=".MainActivity" /> </RelativeLayout>
8. Create a layout file for customizing listview items in the file res/layout/lv_layout.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tv_item" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:paddingLeft="5dp" /> <ToggleButton android:id="@+id/tgl_status" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:focusable="false" android:clickable="false" /> </RelativeLayout>
9. Update the MainActivity class in the file src/in/wptrafficanalyzer/listviewtogglebutton/MainActivity.java
package in.wptrafficanalyzer.listviewtogglebutton; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.SimpleAdapter; import android.widget.Toast; import android.widget.ToggleButton; public class MainActivity extends Activity { String[] countries = new String[] { "India", "Pakistan", "Sri Lanka", "China", "Bangladesh", "Nepal", "Afghanistan", "North Korea", "South Korea", "Japan" }; // Array of booleans to store toggle button status public boolean[] status = { true, false, false, false, false, false, false, false, false, false }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /** Restore from the previous state if exists */ if(savedInstanceState!=null){ status = savedInstanceState.getBooleanArray("status"); } ListView lvCountries = (ListView) findViewById(R.id.lv_countries); OnItemClickListener itemClickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> lv, View item, int position, long id) { ListView lView = (ListView) lv; SimpleAdapter adapter = (SimpleAdapter) lView.getAdapter(); HashMap<String,Object> hm = (HashMap) adapter.getItem(position); /** The clicked Item in the ListView */ RelativeLayout rLayout = (RelativeLayout) item; /** Getting the toggle button corresponding to the clicked item */ ToggleButton tgl = (ToggleButton) rLayout.getChildAt(1); String strStatus = ""; if(tgl.isChecked()){ tgl.setChecked(false); strStatus = "Off"; status[position]=false; }else{ tgl.setChecked(true); strStatus = "On"; status[position]=true; } Toast.makeText(getBaseContext(), (String) hm.get("txt") + " : " + strStatus, Toast.LENGTH_SHORT).show(); } }; lvCountries.setOnItemClickListener(itemClickListener); // Each row in the list stores country name and its status List<HashMap<String,Object>> aList = new ArrayList<HashMap<String,Object>>(); for(int i=0;i<10;i++){ HashMap<String, Object> hm = new HashMap<String,Object>(); hm.put("txt", countries[i]); hm.put("stat",status[i]); aList.add(hm); } // Keys used in Hashmap String[] from = {"txt","stat" }; // Ids of views in listview_layout int[] to = { R.id.tv_item, R.id.tgl_status}; // Instantiating an adapter to store each items // R.layout.listview_layout defines the layout of each item SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.lv_layout, from, to); lvCountries.setAdapter(adapter); } /** Saving the current state of the activity * for configuration changes [ Portrait <=> Landscape ] */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBooleanArray("status", status); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
10. Screenshot of the application
11. Download

12. Testing
Testing of this application is discussed here
13. Reference
http://developer.android.com/guide/index.html

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in
You can hire me on hourly basis or on project basis for Android applications development.
For hiring me, please mail your requirements to info@wptrafficanalyzer.in.
My other blogs
store4js.blogspot.com
Android JSON Parsing with JSONObject and loading to ListView its working but I want Toggle Button in listview for Multiple Choice Selection and store it again in DataBase.
Waiting for reply
Hi,
Please let me know, where did you stuck?
Nice tutorial……..
Can I give you a big hug now!!! Thank you.
When List view is scrolled the Toggle button goes to default state..
Hi sir, can you please help me?
i use two textview with one toggle button.
but i am getting error as
java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.ToggleButton
but your code is working fine for one textview and one toggle button.
please help me with two textviev and one toggle button and getting value from the textview when i on the toggle button
thanks ,waiting for your help..
I want to know , if India toggleButton will send String like DH11,China toggleButton will send String like DH12,How?Thank you.