Search code examples
androiddialogmultiple-choice

setSingleChoiceItems and setPositiveButton Android


Is there a way to turn multiple check box into box that can have only one box checked at time?

So here is something I am trying to solve, with dialog alertbox and singlechoice-multichoice.

public class MainActivity extends Activity {

    CharSequence[] items = {"FIT", "Fakultet za menadzment", "Fakultet digitalnih umetnosti"};
    private String selectedItem;
    public int proba;


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

    }

    private void launchWebPage(String url){
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        startActivity(i);
    }

    public void dialog(View v){
        showDialog(0);
    }

    public void dialog1(View v){
        Toast.makeText(getBaseContext(), "Nema deklarisanu funkciju.", Toast.LENGTH_LONG).show();
    }

    public void dialog2(View v){
        Toast.makeText(getBaseContext(), "Nema deklarisanu funkciju.", Toast.LENGTH_LONG).show();
    }


    public Dialog onCreateDialog(final int id) {

                final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Odabir");
                builder.setSingleChoiceItems(items, 1, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                                selectedItem = (String) items[i];
                                proba = i;


                            }
                        });
                        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int position) {

                                Toast.makeText(getBaseContext(), "Test", Toast.LENGTH_SHORT).show();

                            }
                        });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Toast.makeText(getBaseContext(), "Cancel pritisnuto!", Toast.LENGTH_SHORT).show();
                    }
                });

                builder.show();

        return null;
    }
}

Solution

  • You need to use a radioButon not a checkbox.

    https://developer.android.com/guide/topics/ui/controls/radiobutton.html