Implementing events Spinner with Butter Knife

yaircarreno picture yaircarreno · Jun 6, 2016 · Viewed 9.8k times · Source

First: We need to reference the spinner

@Bind(R.id.field_type_id)
Spinner mTypeIdSpinner;

Second: Create string array

<string-array name="type_id_array">
    <item>One</item>
    <item>Two</item>
    <item>Three</item>
    <item>Four</item>
    <item>Five</item>
</string-array>

Third: Load the adapter in your activity (onCreate method for example)

private void loadSpinnerIdTypes() {
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.type_id_array, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mTypeIdSpinner.setAdapter(adapter);
}

Fourth: Listen the events

@OnItemSelected(R.id.field_type_id)
void onItemSelected(int position) {
    Timber.d("Element selected %s ", mTypeIdSpinner.getItemAtPosition(position));
}

Answer

VizGhar picture VizGhar · Jun 11, 2016

You can use @OnItemSelected with method arguments Spinner and int see example:

@OnItemSelected(R.id.my_spinner)
public void spinnerItemSelected(Spinner spinner, int position) {
    // code here
}

(works with ButterKnife v. 7.0.1)