Home » Android » android – Implementing events Spinner with Butter Knife

android – Implementing events Spinner with Butter Knife

Posted by: admin May 14, 2020 Leave a comment

Questions:

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));
}
How to&Answers:

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)