7arooney 7arooney -4 years ago 196
Android Question

how to add items to the toolbar spinner dynamically in android

I created a simple spinner in tool bar with items in string, I don't need this items in string.xml,I just want add Item through java code
I just want to add items to tool bar spinner dynamically as these item taken from data base in a selects form and this is my Activity code

package abtech.waiteriano.com.actionbartest;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
private android.support.v7.widget.Toolbar toolbar;
private String[] category = {"hello", "this", "is", "me"};

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
category = getResources().getStringArray(R.array.category);
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
// toolbar.setLogo(R.mipmap.ic_launcher);
SpinnerAdapter spinnerAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.category, R.layout.spinner_dropdown_item);
Spinner navigationSpinner = new Spinner(getSupportActionBar().getThemedContext());
navigationSpinner.setAdapter(spinnerAdapter);
toolbar.addView(navigationSpinner, 0);
navigationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this,
"you selected: " + category[position],
Toast.LENGTH_SHORT).show();
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}
});
}
}

Answer Source

You can add your array of string directly into to ArrayAdapter like below :

private String[] category = {"hello", "this", "is", "me"};

Spinner navigationSpinner = new Spinner(getSupportActionBar().getThemedContext());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, category);
navigationSpinner.setAdapter(adapter);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download