问题
I have a little problem with a spinner
.
I create a Spinner
the user click a Button. The Spinner
is shown as it should be, but when onItemSelected
should be called nothing happens.
Here is the code
public void setUpSpinner(){
spinner = new Spinner(this);
CustomArrayAdapter<String> adapter = new CustomArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getAsStrings());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
public void onClick(View view) {
spinner.performClick();
}
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String getName = (String) spinner.getSelectedItem();
getListFromName(getName);
}
Anyone knows what is wrong here?
Thank you guys.
回答1:
Solved the problem by adding a Spinner
in my xml
with height and width set to zero.
回答2:
This looks enough like the turorial, so refer back to that. See below:
I don't see this, but does the main class implement OnItemSelectedListener? Also, You'll want to instantiate the Spinner inside the onCreate() within the main class body.
This line needs to be within the onCreate();
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
回答3:
why do you have spinner = new Spinner(this)
in the set-up ?
surely you already have a Spinner in the XML of your layout, then you simply do spinner = (Spinner) findViewById(R.id.WHATEVER_THE_ID_IS_IN_THE_XML);
so you don't need a new
P.S. this is how I define a Spinner in an XML layout
<Spinner
android:id="@+id/SPINNER_ID"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center_horizontal" />
来源:https://stackoverflow.com/questions/5555549/android-spinner-performclick-onitemselected