Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a spinner with radio buttons

In main.xml I would like to have a spinner1 with two radio buttons and a spinner2 with 3 checkboxes. I don't know how to define and create this spinners in Main.java. Need some help.

main.xml

<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Spinner
android:id="@id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>

spinner1 - needs to have radio buttons and spinner2 need to have multiple checkboxes

main.java

privare Spinner spiner1,spiner2;
public void OnCreate(BUndle SaveInstaceState)
{
super.OnCreate(savedInstanceState);
setContentView(R.layout.main)

spiner1=(Spinner)findViewById(R.id.spinner1);
spiner2=(Spinner)findViewById(R.id.spinner2);

//what to do from here?

}
like image 287
user1222905 Avatar asked Oct 29 '25 18:10

user1222905


2 Answers

create a strings.xml file in res/values/ and add the following:

<?xml version="1.0" encoding="utf-8"?>
  <resources>
<string name="spinnerstr">Choose an item</string>
<string-array name="spinner_array">
    <item>apple</item>
    <item>orange</item>
    <item>grapes</item>
</string-array>

In your spinner.java, add the followoing:

Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
        this, R.array.spinner_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

Hope this will help you.

like image 160
UVM Avatar answered Nov 01 '25 09:11

UVM


Accepted answer doesn't work anymore.

Instead use this to have the radio button look:

adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);

And for those who are using custom layouts, just add android:checkMark="?android:attr/listChoiceIndicatorSingle" and android:gravity="center_vertical" which makes the radio button align with the text.

like image 42
Androidz Avatar answered Nov 01 '25 08:11

Androidz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!