I have a spinner that opens programaticly, and when the user chose an option from the spinner, it closes... is there a way to be notified, or a listener that tells you, when the user chose his choice?
the onItemSelected gets the default item that is chosen automaticly when the spinner is open.
set setOnItemSelectedListener to your spinner...
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Object obj = (Object) parent.getSelectedItem();
//get clicked position from position
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
//this method is call when nothing choosed by you
}
});
Add an OnItemSelectedListener to your Spinner.
I am not sure if I understand your question correctly but let me try to answer it. The normal and straight forward way would be to add an OnItemSelectedListener to the spinner i.e
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// Do whatever you want here
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
});
but this is such a basic thing that I feel like a fool for pointing it out. Anyway here is a tutorial on spinner from Android Developer resources. It creates the listener in step 5 and adds it to spinner on step 6.
Related
i am new to android studio and I am stuck in a scenario, I have a recylerview where all data visible and i want to show data only base on selected city from downlist. any suggestion that how i can achieve that. also guide me that how can I use spinner for filtering
In Spinner to call a method when a item is selected you can use setOnItemSelectedListener()
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// code which needs to be executed when item selected
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
For more details you can visit : https://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener
I am building a simple grocery ordering App with firebase, where I want two spinners and a button.
One Spinner for the item name and item price tag. (For example - 'Chips -5rs-')
Second spinner for the quantity. (for Example - '5 packet')
A button for taking the values from the spinners and putting it to the TextView below. (One item after the other.)
For Example, after adding several items from the spinners, the textview below should look like this. -
Chips -5rs- 5 packet
Biscuits -20rs- 20 packet
Noodles -15rs- 2 packet
and so on..
How do I actually implement it? and if anyone could help me with actual java codes, I would be very thankful. I've also attached a picture below of how I am trying to Implement it. I am new to Android Development and I have keen interest in it.. any help would be deeply appreciated..
:) Thankyou ..
This is the Screenshot of what I am trying to approach.
Define your string global
String priceTag,quantityTag;
then get value from spinner like this
yourSpinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
priceTag= yourSpinner1.spinnerDropDownView.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
same as getting value from your second spinner
yourSpinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
priceTag= yourSpinner1.spinnerDropDownView.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
and show data on button click like this
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
yourtextViewId.setText(priceTag " - " quantityTag);
}
});
You can do it this way,
Firstly grab the values from both the spinners
//From spinner 1
String s1_val = spinner1.getSelectedItemsAsString();
//From spinner 2
String s2_val = spinner2.getSelectedItemsAsString();
Concat the values and set it to the text view.
//concat and set to textView
textView.setText(s1_val.concat(s2.val()));
Perform this on the onClick of Add Items button.
I have one screen with two spinners. The choices in the second spinner depend on the user choice in the first spinner.
Here is my code:
For the first spinner:
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.oman_states));
final MaterialBetterSpinner materialDesignSpinner = (MaterialBetterSpinner)
findViewById(R.id.states_list); // states spinner
materialDesignSpinner.setAdapter(arrayAdapter);
for the second spinner:
final MaterialBetterSpinner materialDesignSpinner2 = (MaterialBetterSpinner)
findViewById(R.id.hospitals_list);
and I implemented the following listener in the second spinner:
materialDesignSpinner2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (materialDesignSpinner.getText().toString() == getString(R.string.muscat)) {
ArrayAdapter<String> muscatHospitals = new ArrayAdapter<>(v.getContext(),
android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.muscat_hospitals));
materialDesignSpinner2.setAdapter(muscatHospitals);
} else if (materialDesignSpinner.getText().toString() == getString(R.string.albatna)) {
ArrayAdapter<String> albatnaHospitals = new ArrayAdapter<>(v.getContext(),
android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.albatan_hospitals));
materialDesignSpinner2.setAdapter(albatnaHospitals);
} else if (materialDesignSpinner.getText().toString() == getString(R.string.musandam)) {
ArrayAdapter<String> smaelHospitals = new ArrayAdapter<>(v.getContext(),
android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.musandam_hospitals));
materialDesignSpinner2.setAdapter(smaelHospitals);
} else if (gm.spinnerChecking(materialDesignSpinner)) {
Toast.makeText(v.getContext(), getString(R.string.choose_state_first), Toast.LENGTH_LONG).show();
}
System.out.println("Working");
}
});
when I press on the spinner, the application crashes
showing the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Filter.filter(java.lang.CharSequence,
android.widget.Filter$FilterListener)' on a null object reference
at
android.widget.AutoCompleteTextView.performFiltering(AutoCompleteTextView.java:971)
at
com.weiwangcn.betterspinner.library.material.MaterialBetterSpinner.onFocusChanged(MaterialBetterSpinner.java:49)
how can I make the second spinner choices based on the first spinner?
UPDATE:
after applying #dominicoder solution, the onItemSelected is not executed for some reason because System.out.println() doesn't print "work" to the console.
Here is the code for the onItemSelected :
materialDesignSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
secondSpinnerAdapter.clear();
secondSpinnerAdapter.addAll(getStringsForPosition(position));
System.out.println("works");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
A couple of things:
Do NOT do string comparisons using == in Java. Use String.equals()
Use the position of the selection of the first spinner to determine what to show, not the text that happens to be showing in that position.
You should update the state of the second spinner in response to the changing of the state of the first spinner, not checking the first spinner state when it's time to show something in the second spinner
You should create just one adapter for your second spinner that you update as needed, instead of creating a new instance each time.
With these suggestions in mind, I would recommend something more like this:
// Second adapter is a class field
private ArrayAdapter<String> secondSpinnerAdapter;
// Initialize it ONCE in onCreate with no items to begin with
secondSpinnerAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_dropdown_item_1line);
materialDesignSpinner2.setAdapter(secondSpinnerAdapter);
// When something is selected in the first adapter,
// update the options in the second adapter
materialDesignSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
secondSpinnerAdapter.clear();
secondSpinnerAdapter.addAll(getStringsForPosition(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
private String[] getStringsForPosition(int position) {
switch(position) {
case 0: return getResources().getStringArray(R.array.musandam_hospitals);
// Add other cases
}
}
This eliminates string equality checks, removes duplication, and makes the intent "when something in the first spinner is a selected, update the options in the second spinner" much clearer.
Hope that helps!
you shouldn't set an on click listener. instead of that do this
materialDesignSpinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I have a OnItemSelectedListener for my Spinner, but it is not called when the selected item is the same as the previous one.I also implemented OnClickListener but it doesn't worked. I have found some solution. But I don't know how can I use it. I need to catch every-time a user click on an item.
JAVA CODE:
spn_filter_category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),String.valueOf(position),Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
XML CODE:
<Spinner
android:id="#+id/spn_filter_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
If you select an different item onItemSelected gets called.
If you don't select a different one it means you have not selected an item, then onNothingSelected gets called.
spn_filter_category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),String.valueOf(position),Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
CharSequence message = "called when the selected item is the same as the previous one";
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
});
This question already has answers here:
Android - How to create clickable listview?
(5 answers)
Closed 8 years ago.
I currently have a ListView id=listview, which I am populating with an ArrayList id=myarraylist. Here is how I do it:
final ListView listview = (ListView) findViewById(android.R.id.list);
myarraylist = (ArrayList<String>) getArray();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mylist);
myarraylist.add(...And then some other stuff I add...);
//This is the part I want to focus on
myarraylist.add("Reset High Scores");
adapter.notifyDataSetChanged();
listview.setAdapter(adapter);
Now, I want the entry Reset High Scores in my ListView to be clickable, and when it is clicked, I want it to do Some Stuff. I know for buttons all you do is set an onClickListener
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
..Some Stuff..
}
});
My question is, how can I make Some Stuff happen when the element Reset High Scores is clicked in the ListView
Edit: This is what I have so far
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#Override
String myString = (String) parent.getAdapter().getItem(position);
if(myString.equals("Clear High Scores")) {
//Stuff
}
}
});
ListView, just like Button, has the ability to set a click listener, but for ListView, the name of the method is setOnItemClickListener(). Instead of using OnClickListener, though, it uses a class called OnItemClickListener, which is more advantageous for using with ListView. The method looks as follows:
yourListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id)
{
// some stuff
}
}
)
Now the advantage of this is that you can check what's contained at the position you've pressed, so the way you could tackle your problem could look something like this:
yourListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id)
{
String myString = (String) parent.getAdapter().getItem(position);
if(myString.equals("Reset High Scores"))
{
// Do what you want
}
}
});
/**
* Creates a new instance
*/
public void onListItemClick(ListView l, View v, int position, long id) {
// Notify the parent activity of selected item
super.onListItemClick(l, v, position, id);
//Do stuff
}
that should get ya started... Andrew is right though.