I have two spinners in a fragment, one of the spinner will display toast message when an item is selected. The problem is the toast in the first if-else statement displayed twice. Once when open the fragment and the second time when the item selected.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.add, container, false);
//------------------------------unit Spinner adapter---------------------------------------//
Spinner spinner = (Spinner) mRootView.findViewById(R.id.units);
//Create ArrayAdapter using string array and default spinner
ArrayAdapter<CharSequence> sAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.units, android.R.layout.simple_spinner_dropdown_item);
//Specify layout to use when list of choices appears
sAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Apply adapter to the spinner
spinner.setAdapter(sAdapter);
//----------------------------reminder Spinner adapter-------------------------------------//
Spinner reminderSpinner = (Spinner) mRootView.findViewById(R.id.list_reminder);
ArrayAdapter<CharSequence> reminderAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.countdown_reminder, android.R.layout.simple_spinner_dropdown_item);
reminderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
reminderSpinner.setAdapter(reminderAdapter);
spinner.setOnItemSelectedListener(spinnerListener);
reminderSpinner.setOnItemSelectedListener(spinnerListener);
return mRootView;
}
//---------------------------------Spinner Listener----------------------------------------//
AdapterView.OnItemSelectedListener spinnerListener = new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()) {
case R.id.units:
String selectedUnit = parent.getItemAtPosition(position).toString();
break;
case R.id.list_reminder:
String reminder = parent.getItemAtPosition(position).toString();
if (reminder.equals("24 hours")) {
Toast.makeText(getActivity(), "Reminder has been set 24 hours from the selected date", Toast.LENGTH_LONG).show();
} else if (reminder.equals("2 days")) {
Toast.makeText(getActivity(), "Reminder has been set 2 days from the selected date", Toast.LENGTH_LONG).show();
} else if (reminder.equals("3 days")) {
Toast.makeText(getActivity(), "Reminder has been set 3 days from the selected date", Toast.LENGTH_LONG).show();
} else if (reminder.equals("1 week")) {
Toast.makeText(getActivity(), "Reminder has been set 1 week from the selected date", Toast.LENGTH_LONG).show();
} else if (reminder.equals("2 weeks")) {
Toast.makeText(getActivity(), "Reminder has been set 2 weeks from the selected date", Toast.LENGTH_LONG).show();
} else if (reminder.equals("1 month")) {
Toast.makeText(getActivity(), "Reminder has been set 1 month from the selected date", Toast.LENGTH_LONG).show();
}
break;
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
};
//------------------------------------end spinner code-------------------------------------//
The '24 hours' toast displayed when user open the fragment and when the '24 hours' selected. I can't figure out what's wrong with the code. Help please?!
Your onItemSelectedListener might be getting called when you set it in onCreateView or it could be getting called when it initially displays the view. One hacky work-around is just to have a boolean that only executes the code in your listener after it has been called at least once before.
IIRC, a spinner must have a selected item no matter what, so it sets the first item when it launches and thus OnItemSelected is fired when the spinner starts up. No way around it unless you want to hack the spinner code.
What you could do is add a counter variable to determine whether or not it is the first time through and not display the toast if it is the first time.
This is because your adpater's onItemSelected is getting called when you are setting the adapter to your spinner. Add a debug point in that if block. A soluion would be to use a boolean flag to check whether the user has selected the spinner or not. Initially make it false. then before your switch check if that flag is false. If it is false then don't perform switch else do it. make the boolean flag true after the switch case. Hence it will be false for the first load and the toast will not appear for when the fragment is loaded.
Related
I have 3 spinners for choosing class, division and subject. These 3 are dependent on each other. I want to enable division's spinner only after selecting a class, and enable subject's spinner after selecting both class and division. and i want to check whether spinners is enable or not when i click on the spinner.
I have done enabling and disabling spinners by using setEnabled like below:
spDivision.setEnabled(true);
spDivision.setEnabled(false);
And, it is working for me.
I have used onitemSelected listener
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
ClassDivData classDivData = (ClassDivData) parent.getItemAtPosition(position);
if(parent == spClass)
{
clsId = classDivData.getId();
// Showing selected spinner item
if(classDivData.getId()>0)
Toast.makeText(parent.getContext(), "Selected: " + classDivData.getId(), Toast.LENGTH_LONG).show();
}
else if(parent == spDivision)
{
divId =classDivData.getId();
// Showing selected spinner item
if (classDivData.getId()>0)
Toast.makeText(parent.getContext(), "Selected: " + classDivData.getId(), Toast.LENGTH_LONG).show();
}
else if(parent == spSubject)
{
subId =classDivData.getId();
// Showing selected spinner item
if (classDivData.getId()>0)
Toast.makeText(parent.getContext(), "Selected: " + classDivData.getId(), Toast.LENGTH_LONG).show();
}
enablingSpinners(); // to enable or disable spinners
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
function enableSpinners() is used to enable or disable spinners
private void enableSpinners() {
if(clsId >-1)
{
spDivision.setEnabled(true);
}
else
{
spDivision.setEnabled(false);
}
if(clsId >-1 && divId >-1)
{
spSubject.setEnabled(true);
}
else {
spSubject.setEnabled(false);
}
}
Note: -1 is the default value of spinners
My problem is i couldn't get the click of the spinner. My need is when i click on the spinner i want to know whether that spinner is enabled or not. Only then i could show the user that he have to select class first for selecting a division.
I have tried setOnClickListener with the spinner.
spDivision.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!spDivision.isEnabled())
{
Toast.makeText(AddHomeWorkActivity.this, "First choose a class", Toast.LENGTH_SHORT).show();
}
}
});
But i got error like below:
Caused by: java.lang.RuntimeException: Don't call setOnClickListener for an AdapterView. You probably want setOnItemClickListener instead
And i tried that too. But got error like below:
Caused by: java.lang.RuntimeException: setOnItemClickListener cannot be used with a spinner.
I have searched a lot for the solution to my problem and so many results. But i didn't get an actual solution to my problem
You should use setOnItemSelectedListener,
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
To know whether your spinner is enabled, use
if(spinner.isEnabled())
So I am having a problem with a spinner not firing the listener when there is only one item in the list.
Here is a break down of what i am trying to do: have a spinner with a string that displays an id/title for an object, there is a button to add items to this spinner that creates a dialog and returns and object from the dialog and updates the spinner. I currently have the spinner working to add items to the spinner after the dialog closes. the code works as intended when there are multiple items in the spinner, however if there is only one item in the spinner then no onitemselectedlistener is fired. I know this because i have debugged the code and walked over the listener, when trying to select an item when there is only one item in the list does nothing. However, if i add another item to this list i am able to select it but only after first selecting the second or third so on item in the list
it is almost as if this item is if this is the item the spinner is currently selecting and therefore not generating any event for pressing it. I suppose my question would be how do i clear the spinner selection so that there is no Current selection. or would i have to do something like always have an entry in the spinner that says "Choose One" and have a check that would only do some action if the spinner's current selection wasn't equivalent to "Choose One".
my listener as it currently stands
methodSpin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(first == false) {
body.setText("");
currentMethod = hold.get(position);
Toast.makeText(methodActivity.this, "Text!" + position + ":" + currentMethod.body, Toast.LENGTH_SHORT).show();// for feedback/testing purposes
body.setEnabled(true);
body.setText(currentMethod.body);
}
else
Toast.makeText(methodActivity.this, "check == false", Toast.LENGTH_SHORT).show(); // for feedback/testing purposes
}
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(methodActivity.this, "onNothingSelected", Toast.LENGTH_SHORT).show();// for feedback/testing purposes
}
});
The Spinner will always have a selected item even if you call Spinner.setSelection( -1 ). I guess what you can do it to add a prompt
as the first option.
ArrayList<String> aOptions = new ArrayList<String>();
aOptions.add("Choose One");
aOptions.add("Option 1");
ArrayAdapter<String> adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_dropdown_item, aOptions);
Spinner spinner = (Spinner)findViewById(R.id.spinner);
spinner.setAdapter(adapter);
I am experiencing a odd problem. My OnItemSelectedListener seems only works one time, i mean that it shows my test Toast at the first time when clicking the coresponding items, but it doesn't show the test Toast when i hit the same item at the second time.( it does work when clicking a different item at the second time) What is the problem? plz help me
partial code is here
//get task object from menu
taskListArr = new ArrayList<Task>();
taskListArr = getCurrentTasks(taskListArr);
myTask=new TaskListAdapter(this, 0, taskListArr);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, TaskModel.sorts);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sortSpinner.setAdapter(aa);
sortSpinner.setOnItemSelectedListener(this);
#SuppressWarnings("unchecked")
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if(arg2 == 0){
Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_SHORT).show();
Collections.sort(taskListArr);
taskListView.setAdapter(myTask);
}
if(arg2 == 1){
Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_SHORT).show();
Collections.sort(taskListArr, new DateComparator());
taskListView.setAdapter(myTask);
}
if(arg2 == 2){
Toast.makeText(getApplicationContext(), "3", Toast.LENGTH_SHORT).show();
Collections.sort(taskListArr, new PriorityComparator());
taskListView.setAdapter(myTask);
}
position = arg2;
}
public void onNothingSelected(AdapterView<?> arg0) {
}
Check out spinner in android developers site http://developer.android.com/reference/android/widget/Spinner.html
A view that displays one child at a time and lets the user pick among them. The items in the Spinner come from the Adapter associated with this view.
It selects one child at a time. So Selecting the already selected child again will not invoke onItemSelected function.
i agree with user936414 answer he is right but if still you want that your toast come again then add a on touch listener on your spinner and in the ontouch event add this
line sortSpinner.setOnItemSelectedListener(this);
by this each time as you touch your spinner listener will get invoked again and you will get the on itemselected each time
I am using simple_list_item_multiple_choice with list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); to create a list of check boxes populated from a database query. I am then using onListItemClick to handle the clicking of the list, again that is working fine. What I can find no way of doing (after 5 days) is writing an if statement based on whether or not the check box attached to the list item is checked. What I need is the equivalent of the example below which works perfectly for a check box where I can use the android:onClick element to fire the method below.
public void onCheckboxClicked(View v) {
// Perform action on clicks, depending on whether it's now checked
if (((CheckBox) v).isChecked()) {
Toast.makeText(this, "Selected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Not selected", Toast.LENGTH_SHORT).show();
}
}
This is critical to my app so any advice would be greatly appreciated. Below is the simpleCusrorAdapter is am using:
Cursor cursor3 = db.rawQuery("SELECT _id, symname FROM tblsymptoms WHERE _id IN ("+sympresult+") ", null);
adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_multiple_choice,
cursor3,
new String[] {"symname","_id"},
new int[] {android.R.id.text1});
setListAdapter(adapter);
ListView list=getListView();
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
I have solved the problem after finding this very useful blog item
I changed my onListItemClick to the following and it works like a dream:
public void onListItemClick(ListView parent, View view, int position, long id) {
CheckedTextView check = (CheckedTextView)view;
check.setChecked(!check.isChecked());
boolean click = !check.isChecked();
check.setChecked(click);
if (click) {
Toast.makeText(this, "Not Selected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Selected", Toast.LENGTH_SHORT).show();
}
}
If I understand correctly, each row in your list has a checkbox. When an item in the list is selected you want to be able to tell if the corresponding checkbox is checked?
Try to use the setTag(...) method on each list item View object. Then when onListItemClick() method is called you can call getTag(...) on the view (which will return your checkbox). I assume that you are using a custom Adapter to populate the list. While populating you want to call:
setTag( CHECKBOX_KEY, checkbox );
For example:
protected void onListItemClick(ListView l, View v, int position, long id) {
CheckBox cb = (CheckBox)v.getTag( CHECKBOX_KEY );
boolean isChecked = false;
if( null != cb ) {
isChecked = cb.isChecked();
}
// .. do whatever you have to here...
}
Hope this helps...
Spinner OnclickListener event executes twice -
Spinner initialization
User selected manually
where as implementation of listener is as :
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
Problem definition
I want to save user selected text into data storage, when user choose any item from spinner, and I am able to do this. But my another task is that to show previously selected item (access from data storage) as selected item in spinner, but each time when I call spinner's activity, spinner shows first item as default selected item, and also in data storage it make change previous item to default.
How can I make difference between 'Spinner initialization' and 'User selected manually' events?
You have to handle both events logically. As these references (Android Spinner selection, problem on spinner) says that you have to use flag variable to handle this, I am putting a code sample.
Hope this will help you to clear your logic.
public class TestActivity extends Activity {
//Checks report spinner selection is default or user selected item
private boolean isDefaultSelection;
//Spinner setup
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
// Set true at onCreate
isDefaultSelection = true;
spinner = (Spinner) findViewById(R.id.id_of_spinner);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String> (this, R.layout.drop_down_custom_row, data);
//Implement custom view for drop down of spinner
//spinnerAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(isDefaultSelection) { //If spinner initializes
spinner.setSelection("Set_here_id_of_data_item_from_storage_which_was_previously_stored");
isDefaultSelection = false;
} else { //If user manually select item
int itemPosition = spinner.getSelectedItemPosition();
//Write here code to store selection (itemPosition) of user into data storage
}
}
public void onNothingSelected(AdapterView<?> parent) {
//User selected same item. Nothing to do.
}
});
}
}
Hope it will clear your doubt.
You can call the setSelection at the same time that the items are added to the adapter, see this example: How to avoid onItemSelected to be called twice in Spinners