I'm building the a app which has more than 20 spinners. I'm trying to reset all spinners with one click. is that possible? could you please guide me on how to achieve this. below is my codes.
If possible i want the reset to be selected from menu ( 3 dots on top right) can someone please assist me. thank you in advance :)
package com.example.hfacs_test09;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class Unsafe extends Fragment implements OnItemSelectedListener {
private Spinner uhs1a,uhs1b,uhs1c;
private TextView unsaferesult;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.unsafe, container, false);
unsaferesult = (TextView) rootView.findViewById(R.id.unsaferesult);
uhs1a = (Spinner) rootView.findViewById(R.id.uhs1a);
uhs1b = (Spinner) rootView.findViewById(R.id.uhs1b);
uhs1c = (Spinner) rootView.findViewById(R.id.uhs1c);
uhs1a.setOnItemSelectedListener(this);
uhs1b.setOnItemSelectedListener(this);
uhs1c.setOnItemSelectedListener(this);
return rootView;
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id){
//uhs1a.setSelection(position);
int r1 = Integer.valueOf((String) uhs1a.getSelectedItem());
int r2 = Integer.valueOf((String) uhs1b.getSelectedItem());
int r3 = Integer.valueOf((String) uhs1c.getSelectedItem());
int total = r1 + r2 + r3;
//int myresult = (Integer) uhs1a.getSelectedItem() ;
unsaferesult.setText("Total Score is " + total);
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
To reset a spinner to default value:
uhs1a = (Spinner) rootView.findViewById(R.id.uhs1a); // Ignore this if you already did that in onCreateView
uhs1a.setSelection(0); // Assuming the default position is 0.
To do that for all the spinners, either you do that manually for every spinner, or you add all spinners to an ArrayList and then
for(int i=0; i < myArrayList.size(); i++)
myArrayList.get(i).setSelection(0);
To do that from the Menu (3 dots) button:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.your_menu_xml_file, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.reset_button:
// Reset spinners here.
return true;
default:
return super.onOptionsItemSelected(item);
}
}
It is same as single spinner.
spinner.setSelection(position);
just do this for all the spinners in your onclick of the button method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With