Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combobox in Android

I need something like a combobox in access in android, i want to choose the customer per name, but in the background the id should be chosen. how to do?

like image 227
Mark Avatar asked Mar 14 '11 08:03

Mark


2 Answers

In android comboboxes are called spinner. Nevertheless, gnugu has posted in his blog his own implementation of a combobox. http://www.gnugu.com/node/57

A simple example of an spinner would be the following. First, edit your XML code with something like this

Spinner android:id="@+id/Spinner01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

Your java code should include something like this, the options are very intuitive. If you are using eclipse it will suggest you some options

public class SpinnerExample extends Activity {
    private String array_spinner[];
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Here come all the options that you wish to show depending on the
        // size of the array.
        array_spinner=new String[5];
        array_spinner[0]="option 1";
        array_spinner[1]="option 2";
        array_spinner[2]="option 3";
        array_spinner[3]="option 4";
        array_spinner[4]="option 5";
        Spinner s = (Spinner) findViewById(R.id.Spinner01);
        ArrayAdapter adapter = new ArrayAdapter(this,
        android.R.layout.simple_spinner_item, array_spinner);
        s.setAdapter(adapter);
    }
}
like image 174
dLobatog Avatar answered Oct 07 '22 13:10

dLobatog


An alternate solution to the need to link Customer ID to the selected Item.

To have a simple selector with text you cause make use of the array resources Setup the Spinner in XML

<Spinner android:id="@+id/spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/colors"/>

If you need more data linked with the spinner you can use Objects to populate the spinner. The default functionality of an ArrayAdapter is to call toString() on any object and pass that to the view.

if (item instanceof CharSequence) {
    text.setText((CharSequence)item);
} else {
    text.setText(item.toString());
}

You can implement toString() in your object and it will display correctly in the spinner. Then to get the data back from the array you can add a handler onto ItemSelected and get the object back from the seed array or the ArrayAdapter.

ArrayAdapter adapter = new ArrayAdapter(activity, android.R.layout.simple_spinner_item, arrayOfObjects);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
    {
        Log.d(arrayOfObjects[position]._id);
    }

});
like image 24
Steven Avatar answered Oct 07 '22 13:10

Steven