Wednesday, September 25, 2013

ListView with Checkbox android example



Download Full Source Code : Source Code



  • Create new project named "ListviewWithCheckbox".
  • add following code in activity_main.xml file.

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffeeeeee"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Country Codes"
        android:textSize="20sp" />

    <Button
        android:id="@+id/findSelected"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get Selected Items" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>


  • Add below code in MainActivity.java file.

MainActivity.java



public class MainActivity extends Activity {

MyCustomAdapter dataAdapter = null;

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

// Generate list View from ArrayList
displayListView();

checkButtonClick();

}

private void displayListView() {

// Array list of countries
ArrayList<States> stateList = new ArrayList<States>();

States _states = new States("91", "India", false);
stateList.add(_states);
_states = new States("61", "Australia", true);
stateList.add(_states);
_states = new States("55", "Brazil", false);
stateList.add(_states);
_states = new States("86", "China", true);
stateList.add(_states);
_states = new States("49", "Germany", true);
stateList.add(_states);
_states = new States("36", "Hungary", false);
stateList.add(_states);
_states = new States("39", "Italy", false);
stateList.add(_states);
_states = new States("1", "US", false);
stateList.add(_states);
_states = new States("44", "UK", false);
stateList.add(_states);

// create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(this, R.layout.state_info, stateList);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);

listView.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
States state = (States) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
"Clicked on : " + state.getName(), Toast.LENGTH_LONG)
.show();
}
});
}

private class MyCustomAdapter extends ArrayAdapter<States> {

private ArrayList<States> stateList;

public MyCustomAdapter(Context context, int textViewResourceId,

ArrayList<States> stateList) {
super(context, textViewResourceId, stateList);
this.stateList = new ArrayList<States>();
this.stateList.addAll(stateList);
}

private class ViewHolder {
TextView code;
CheckBox name;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

ViewHolder holder = null;

Log.v("ConvertView", String.valueOf(position));

if (convertView == null) {

LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

convertView = vi.inflate(R.layout.state_info, null);

holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView
.findViewById(R.id.checkBox1);

convertView.setTag(holder);

holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
States _state = (States) cb.getTag();

Toast.makeText(
getApplicationContext(),
"Checkbox: " + cb.getText() + " -> "
+ cb.isChecked(), Toast.LENGTH_LONG)
.show();

_state.setSelected(cb.isChecked());
}
});

} else {
holder = (ViewHolder) convertView.getTag();
}

States state = stateList.get(position);

holder.code.setText(" (" + state.getCode() + ")");
holder.name.setText(state.getName());
holder.name.setChecked(state.isSelected());

holder.name.setTag(state);

return convertView;
}

}

private void checkButtonClick() {

Button myButton = (Button) findViewById(R.id.findSelected);

myButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

StringBuffer responseText = new StringBuffer();
responseText.append("Selected Countries are...\n");

ArrayList<States> stateList = dataAdapter.stateList;

for (int i = 0; i < stateList.size(); i++) {
States state = stateList.get(i);

if (state.isSelected()) {
responseText.append("\n" + state.getName());
}
}

Toast.makeText(getApplicationContext(), responseText,
Toast.LENGTH_LONG).show();
}
});
}

}



  • Create new POJO java class,Which is used for getters and setters methods.Named it States.java. 

States.java



public class States {

String code = null;
String name = null;
boolean selected = false;

public States(String code, String name, boolean selected) {
super();
this.code = code;
this.name = name;
this.selected = selected;
}

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public String getName() {
return name;
}

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

public boolean isSelected() {
return selected;
}

public void setSelected(boolean selected) {
this.selected = selected;
}

}

  • Create new XML layout file, which is used to integrate CheckBox and TextView in ListView.Named it state_info.xml.

state_info.xml


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

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:text="checkbox"
        android:textColor="#B40404" />

    <TextView
        android:id="@+id/code"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@id/checkBox1"
        android:layout_alignBottom="@id/checkBox1"
        android:layout_toRightOf="@id/checkBox1"
        android:text="textview"
        android:textColor="#ff000000" />

</RelativeLayout>


  • Done ! Now run the project.


Download Full Source Code : Source Code



11 comments:

  1. Your blog is very helpful for me. I’m surely coming again to read these articles and blog.

    ReplyDelete
  2. can you tell me howa to retrieve the mobile contacts using the ListView with checkbox??

    ReplyDelete
    Replies
    1. Sure.
      I will upload full code on blog soon.Please stay tune with us.

      Delete
    2. Check this below link:
      http://developerandro.blogspot.in/2014/05/contact-list-with-checkbox-part-1.html

      Delete
  3. can you tell me how to apply longclicktodetele on the listview that have checkbox,i want the listview can be add edit and delete

    ReplyDelete
  4. Thank you for your nice post.
    I have a problem when i try to load a image in getView:
    with imageLoader.displayImage(imageUri, imageView);
    please help me out?

    ReplyDelete
    Replies
    1. solved:
      by call the next line first
      ImageLoader imgLoader = new ImageLoader(getApplicationContext());

      Delete
  5. Is it possible to have the Adapter in a new class file?

    ReplyDelete
  6. how to retrive data from mysql database and show them into listview with checkboxes ..can you plaese help me..

    ReplyDelete