Malvinka
Malvinka

Reputation: 1389

listview with checkbox android

To my app I need a list with checkboxex, where clicking on text causes new intent but clicking on the checkbox causes saving of checkbox's value. I am not sure if my problem is clear so here is my example:

I got a list ( '_' are checkboxes):

Let's click on checkbox's placed next to A and C:

Let's click on 'valueA' textView. Now the new intent should start and vector [valueA, valueC] should be saved and send to next intent.

For tests I create a list where each item is linearView with textView and checkbox. I created two methods: onClick_textView and onClick_checkBox. In this methods and in 'onListItemClick' I just show toasts to test which one is executed. The only one that works in onClick_checkBox. I do not know even where to start with this task. Could you show me some hints? Useful methods, proper docs sites, algorithm's draft maybe?

Upvotes: 0

Views: 621

Answers (1)

dchks11
dchks11

Reputation: 695

Please refer to below code:

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;
}

}

MainActivity.java File

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();
        }
    });
}

}

activity_main.xml file

<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>

state_info.xml file

 <?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>

You can also refer to this link http://developerandro.blogspot.com/2013/09/listview-with-checkbox-android-example.html

Upvotes: 1

Related Questions