Reputation: 369
In my app I have a spinner that shows a list of elements. The user is able to select one of them and next click on a "Confirm" button. However, the element list may also be empty: in this case I don't want the button to be enabled. I tried to accomplish this behaviour programmatically, but I didn't succeed: the button appears always as enabled. What am I missing? Here's my code:
Spinner dropdownProperty;
AppCompatButton confirmBtn;
...
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dropdownProperty.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
if(dropdownProperty.getSelectedItem().toString().equals(""))
confirmBtn.setEnabled(false);
else confirmBtn.setEnabled(true);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
...
}
I've also tried to manage the situation in the onNothingSelected method but it didn't help.
Any idea? Thank you
Upvotes: 0
Views: 194
Reputation: 634
You should keep your button disabled by default in XML of the view or if you are creating the button in java then keep it disabled when creating it. Enable it only when an item is selected from the spinner.
Upvotes: 0
Reputation: 29
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//first disable confirm button
confirmBtn.setEnabled(false);
dropdownProperty.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
if(dropdownProperty.getSelectedItem().toString().equals(""))
confirmBtn.setEnabled(false);
else confirmBtn.setEnabled(true);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
...
}
Note: initially if u have default value selected, then this may be modified.
Upvotes: 0
Reputation: 54204
You are enabling/disabling your Button
only inside the OnItemSelectedListener
, which means that the user actually has to choose an item in order for you to set the Button's state. If there are no items to choose, that's never going to happen.
You should instead enable/disable the Button
any time the items in the dropdown change. I can't see the rest of your code, but presumably you are setting up your dropdownProperty
with some list. Just check to see if the list is empty or not and set the Button's state accordingly.
Upvotes: 1