So, I have a checkbox. When I check this checkbox, I do not want the box to check right away. I have a dialog pop up and ask the user "Mark as complete/incomplete" or "Cancel". Only when the user selects "Mark as complete/incomplete" do I want the checkbox to toggle. But, whenever I click on this option, the dialog reappears and the checkbox is not toggled. I'm not sure what I am doing wrong here. Here is my code:
package com.example.testcheckbox;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.CheckBox;
import android.widget.CompoundButton;
public class MainActivity extends ActionBarActivity {
CheckBox cb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cb = (CheckBox) findViewById(R.id.checkbox);
cb.setChecked(true);
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
final boolean isChecked) {
CharSequence options[];
if (isChecked) {
cb.setChecked(false);
options = new CharSequence[] { "Mark as Complete",
"Cancel" };
} else {
cb.setChecked(true);
options = new CharSequence[] { "Mark as Incomplete", "Cancel" };
}
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
cb.toggle();
}
}
});
builder.show();
}
});
}
}
and here is the layout with the checkbox:
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.testcheckbox.MainActivity" >
<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
Any ideas? If you don't understand what I want to do, just ask! Thanks
Aucun commentaire:
Enregistrer un commentaire