why doesn't fragment support spinners in it? I have the following fragment class and added spinners to it.
public class SettingFragment extends Fragment {
Spinner spinner1;
public List<String> genderitems, titleitems;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootview = inflater.inflate(R.layout.settinglayout, container,
false);
spinner1 = (Spinner) rootview.findViewById(R.id.usertitle);
titleitems = new ArrayList<String>();
setTitleSpinnerContent(rootview);
titleitems.add("Beginner");
titleitems.add("Novice");
return rootview;
}
private void setTitleSpinnerContent(View view) {
ArrayAdapter<String> adp = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_dropdown_item_1line, titleitems);
adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adp);
}}
How to get the spinner change value upon selection and add it a textview on the spinner.
What is that i am missing here? Thanks in advance.
I tried even adding onitemselectedlistener() but too the result is nil.
There are no differences in adding spinners in activity and fragment. If u want to get the spinner item changed listener implement like this..
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
Toast.makeText(parent.getContext(),
"On Item Select : \n" + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
I'm a bit confused as to what your specific problem is, but if the problem is that you aren't seeing your spinner populated with the values 'Beginner' and 'Novice', it looks like have set your adapter on the empty list, and then added items to the list after the adapter is set. But you never called notifyDataSetChanged() on your adapter, so it doesn't know about your new values. Have you tried the simple solution of adding the items to your list before you set the adapter?
titleitems.add("Beginner");
titleitems.add("Novice");
setTitleSpinnerContent(rootview);
Related
I am trying to obtain the selected value from a spinner to store it and use it later. I have tried in two different ways:
return null value
print only the first value of the list, when I select another value it does not print anything.
way 1
public class genera_debate extends Fragment implements AdapterView.OnItemSelectedListener {
public String text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_genera_debate,container,false);
list_of_interest =view.findViewById(R.id.subject_of_interest);
String [] subject = {"Tema de interés","Política","Deporte","Animales","Videojuegos","Economía","Medicina","Cultura","Ciencia","Tecnología","Música","Otros"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, subject);
list_of_interest.setAdapter(adapter);
list_of_interest.setOnItemSelectedListener(this);
Toast.makeText(getActivity(), "value is"+text, Toast.LENGTH_SHORT).show();
return view;}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
text=list_of_interest.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
way 2
public class genera_debate extends Fragment implements AdapterView.OnItemSelectedListener {
public String text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_genera_debate,container,false);
list_of_interest =view.findViewById(R.id.subject_of_interest);
String [] subject = {"Tema de interés","Política","Deporte","Animales","Videojuegos","Economía","Medicina","Cultura","Ciencia","Tecnología","Música","Otros"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, subject);
list_of_interest.setAdapter(adapter);
list_of_interest.setOnItemSelectedListener(this);
text=list_of_interest.getSelectedItem().toString();
Toast.makeText(getActivity(), "value is"+text, Toast.LENGTH_SHORT).show();
return view;}
}
I hope you can help me, regards
Define your Toast inside the onItemSelectedListener method.
The problem here is that the Toast is being called when your view is being created as it is inside the onCreate method which is called once your activity starts hence your Toast is being called only when your view is being created that means only once.
If you want it to be appeared every time you select a new value you need to define it inside the onItemSelectedListener as this method will be called every time you select a new value in the drop down .
Hope this helps you.
i create in a two way data binding spinner in Android, and added value into with a result of a REST GET.
I need now to add the first value of the spinner as an empty string that when it will be selected from the spinner, the value will be null.
In the fragment class i wrote this code:
//spinner
appCompatSpinner = binding.spinner;
spinnerAdapter = new SpinnerAdapter(getActivity(), viewModel.usersDetailsList );
appCompatSpinner.setAdapter(spinnerActorAdapter);
appCompatSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
viewModel.onSelected(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
mAdapter.notifyDataSetChanged();
Can someone please help me to achieve that?
I'm new to Android development, I having some problem which unable to resolve.
I tried to implement a Spinner inside Fragment, now it having problems with the spinner.setOnItemClickListener() method,
It showing an error message:
"setOnItemClickListener
(android.widget.AdapterView.OnItemClickListener) in Spinner cannot be
applied to (anonymous
android.widget.AdapterView.OnItemSelectedListener)
Here is my code:
public class CheckAvailabilityFragment extends Fragment {
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_check_availability, container,false);
spinner = (Spinner)getView().findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(getActivity().getBaseContext(),R.array.venue,android.R.layout.simple_list_item_1);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemClickListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return rootView;
}
}
The error message tells you that setOnItemClickListener() takes a parameter of type OnItemClickListener. However, you are giving it a OnItemSelectedListener. Since Spinner doesn't support OnItemClickListener, you probably mean to call onItemSelectedListener() which takes a OnItemSelectedListener as its parameter.
setOnItemClickListener will not works with spinner as been said at Spinner SetOnItemClickListener:
A spinner does not support item click events. Calling this method will
raise an exception.
Instead use
setOnItemSelectedListener(AdapterView.OnItemSelectedListener).
Try using the following:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
use getActivity() instead of getBaseContext()
Is there a reason you want getBaseContext()? You should be able to just pass getActivity() as the first parameter of createFromResource()
Long version I have two spinners on my screen and when I select the one, I do certain operations, and the other spinner should display the original selection, because of design patterns. In this situation, I let the user select the elements on a list by year, and by state. You would agree with me that when the user choose to select by year, the spinner regarding the state should display the default selection (the one that displays all of the item) and not the last selected one.
I am trying to do this from this morning, but when I found this solution I really though I was done.
Short version I want to setSelection(0) on the spinner which is not clicked, without triggering its listener (which by the way, will setSelection(0) on the first spinner, if triggered)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
// irrelevant code...
mYearSpinner.setOnItemSelectedListener(onYearSelected);
mStateSpinner.setOnItemSelectedListener(onStateSelected);
// irrelevant code...
}
private AdapterView.OnItemSelectedListener onYearSelected = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mStateSpinner.setOnItemSelectedListener(null);
mStateSpinner.setSelection(0);
mStateSpinner.setOnItemSelectedListener(onStateSelected);
// Do something...
}
#Override
public void onNothingSelected(AdapterView<?> parent) { }
};
private AdapterView.OnItemSelectedListener onStateSelected = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mYearSpinner.setOnItemSelectedListener(null);
mYearSpinner.setSelection(0);
mYearSpinner.setOnItemSelectedListener(onYearSelected);
// Do something...
}
#Override
public void onNothingSelected(AdapterView<?> parent) { }
};
But no! The listeners will just fire, indiscriminately.
Is there someone who knows how to handle this problem?
Why this solution wouldn't work?
As requested, here is the full code of my onCreateView(...) method
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
Log.d(TAG, "onCreateView");
View view = inflater.inflate(R.layout.fragment_career, container, false);
mExamListView = (ListView) view.findViewById(R.id.exam_list_view);
mYearSpinner = (Spinner) view.findViewById(R.id.select_by_year_spinner);
mStateSpinner = (Spinner) view.findViewById(R.id.select_by_state_spinner);
mLoadingView = view.findViewById(R.id.fragment_career_loading_spinner);
mExamListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Exam exam = (Exam) parent.getItemAtPosition(position);
if (exam.isBookable()) {
FragmentManager fm = getActivity().getSupportFragmentManager();
SessionsDialogFragment.newInstance(exam).show(fm, null);
}
}
});
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> yearAdapter = ArrayAdapter.createFromResource(getActivity(),
R.array.spinner_year, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
yearAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> stateAdapter = ArrayAdapter.createFromResource(getActivity(),
R.array.spinner_state, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mYearSpinner.setAdapter(yearAdapter);
mStateSpinner.setAdapter(stateAdapter);
mYearSpinner.setOnItemSelectedListener(onYearSelected);
mStateSpinner.setOnItemSelectedListener(onStateSelected);
return view;
}
I tried implementing what --- suggested and I want to report here what happens.
When the application starts all the two listeners are executed only once.
Then, if I select an item on the first spinner (let's say the year spinner), the expected listener is executed only once (as it should be), and so it is, if I keep selecting items on it.
Ultimately, if I select and item on the state spinner, the listeners are executed in this way
1. onStateListener
2. onYearListener
3. onStateListener
From reading your comments it sounds like you want to set the selection of a second spinner to 0 from your first spinners onItemClick method without triggering its listener.
If you keep a record of the old position the spinners are at in integer variables we can check if the position has changed and only run the code if it has.
That way if we set the old position variable to 0 before changing the spinners current position to 0 it will think its position hasn't changed and so won't run the code in the listener.
private AdapterView.OnItemSelectedListener onYearSelected = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (lastYearPosition != position) {
//Do you code here
lastStatePosition = 0;
mStateSpinner.setSelection(0);
}
lastYearPosition = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) { }
};
private AdapterView.OnItemSelectedListener onStateSelected = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (lastStatePosition != position) {
//Do your code here
lastYearPosition = 0;
mYearSpinner.setSelection(0);
}
lastStatePosition = position;
}
My activity contains a button and a ListView. The ListView contains a Spinner and an EditText view. I use the button each time I want to insert a new row entry in my Activity's ListView.
I have followed the instructions of previous stackoverflow threads like this one here: Android Listview with spinner and a checkbox on how to populate ListViews with focusable objects like Spinners.
My problem is that each time I dynamically add a new ListView entry in the ListView, the Spinner value of the previous ListView entry is lost (actuall the Spinner returns to its default setting). Say for simplicity that my Spinners are populated with the following data:
String spinner_data[] = {"apple", "banana", "pear", "watermelon", "strawberry"};
For example, if I select my first ListView's Spinner value to be "pear" and then I add a new ListView entry with my Button, the "pear" entry disappears from the 1st ListView Spinner and the default value "apple" appears).
Any help is appreciated!
This is my activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView) findViewById(R.id.lv);
da = new DataAdapter(this, new ArrayList<RawData>());
lv.setAdapter(da);
btn_new = (Button)findViewById(R.id.btn_new);
btn_new.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
da.add(new RawData(this));
da.notifyDataSetChanged();
}
});
}
The RawData class is this one:
public class RawData {
private int selected_position;
private ArrayAdapter<CharSequence> adapter;
public RawData(Context context)
{
adapter = ArrayAdapter.createFromResource(context, R.array.data, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
public ArrayAdapter<CharSequence> getAdapter()
{
return adapter;
}
/**
* get adapter's item text from selected position
* #return
*/
public String getText()
{
return (String) adapter.getItem(selected_position);
}
public int getSelected()
{
return selected_position;
}
public void setSelected(int selected)
{
this.selected_position = selected;
}
}
The DataArrayAdapter is the following:
public class DataArrayAdapter extends ArrayAdapter<RawData> {
private Activity myContext;
//private final List<RawData> list;
public DataArrayAdapter(Activity context, List<RawData> list)
{
super(context, R.layout.row_view, list);
myContext = context;
}
static class ViewHolder
{
protected RawData data;
protected Spinner spn;
protected EditText edt;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = null;
if ( convertView == null )
{
LayoutInflater inflator = myContext.getLayoutInflater();
view = inflator.inflate(R.layout.row_view, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.edt = (EditText)view.findViewById(R.id.edt);
viewHolder.data = new RawData(myContext);
viewHolder.spn = (Spinner)view.findViewById(R.id.spn);
viewHolder.spn.setAdapter(viewHolder.data.getAdapter());
viewHolder.spn.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2_position, long arg3) {
// TODO Auto-generated method stub
viewHolder.data.setSelected(arg2_position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
// Update the TextView to reflect what's in the Spinner
view.setTag(viewHolder);
}
else
{
view = convertView;
}
// This is what gets called every time the ListView refreshes
ViewHolder holder = (ViewHolder) view.getTag();
holder.spn.setSelection(getItem(position).getSelected());
return view;
}
}
You're not handling the situation when getView gets a non-null convertView. In your example, after you add an item, ListView refreshes itself, and position that should display 'pear' gets an existing convertView (the one that was used previously to display 'apple') and you just pass it along to ListView without setting the data for current position. You cannot rely on ListView items to store any data, you should always set correct contents for position in getView method of your adapter.
Just to be clear, I see that your code sets the selected position in the end of getView but the issue is that whatever is tagged to your convertView when it is passed to getView by recycler mechanism in ListView is random and can be associated with any position it used to display before.
To make your application work you'll have to create array of selectedItem values for all your spinners, and attach it as a member to your adapter. You'll have to update the corresponding value on each OnItemSelected event and you'll add a new value for each "add" button click. And when you prepare your view in getView you'll just set the selected spinners index to corresponding value in your array.