Spinner prompt doesn't show up - android

I want to use spinner prompt like "Select City". I did set a value for select_city in string layout use in layout android:prompt="#string/select_city" but it did not work. Also tried to use sp_city.setPrompt("Select City"); also did not work.
What is my problem? How can I fix it and set the prompt?
Layout:
<Spinner
android:id="#+id/spinner_poi_city"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/btn_dropdown"
android:spinnerMode="dropdown"/>
Class:
public class FirstPOIPreference extends DialogPreference {
private Spinner sp_city;
private ArrayAdapter<String> adapter;
private POI poiDialog = new POI();
public FirstPOIPreference(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
setPersistent(false);
setDialogLayoutResource(R.layout.pref_poi_dialog);
setPositiveButtonText(android.R.string.ok);
setNegativeButtonText(android.R.string.cancel);
}
#Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
initViews(view);
}
private void initViews(View view) {
sp_city = (Spinner) view.findViewById(R.id.spinner_poi_city);
sp_city.setPrompt("City");
String[] arrayCity = new String[]{"Erie", "Pittsburgh", "Cleveland", "Buffalo", "Niagara Falls", "Jamestown"};
adapter = new ArrayAdapter <> (this.getContext(), android.R.layout.simple_spinner_dropdown_item, arrayCity);
sp_city.setAdapter(adapter);
sp_city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView <?> parentView, View selectedItemView, int position, long id) {
poiDialog.setCity(sp_city.getSelectedItem().toString());
}
#Override
public void onNothingSelected(AdapterView <?> parentView) {
}
});
}
}

you can do it this way, i have done it as some tricky way.it helps you
private void initViews(View view) {
sp_city = (Spinner) view.findViewById(R.id.spinner_poi_city);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
if (position == getCount()) {
((TextView) v.findViewById(android.R.id.text1)).setText("");
((TextView) v.findViewById(android.R.id.text1)).setHint(getItem(getCount())); //"Hint to be displayed"
}
return v;
}
#Override
public int getCount() {
return super.getCount() - 1; // you dont display last item. It is used as hint.
}
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Erie");
adapter.add("Pittsburgh");
adapter.add("Cleveland");
adapter.add("Buffalo");
adapter.add("Niagara Falls");
adapter.add("Jamestown");
adapter.add("Select City"); //This is the text that will be displayed as hint.
sp_city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String spinnerValue = String.valueOf(sp_city.getSelectedItem().toString());
if (!spinnerValue.equalsIgnoreCase("Select City")) {
//do your code
Toast.makeText(this, sp_city.getSelectedItem().toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
sp_city.setAdapter(adapter);
sp_city.setSelection(adapter.getCount()); //set the hint the default selection so it appears on launch.
}

I think better solution is to use "Select City" as a first item of the array thats you will add to spinner. So by default it will show Select city. And you can check if city is selected or not by checking spinner selected position. If position is 0 show toast or something like "Please select city."

You are mistaking prompt with default text.
Tap on the spinner and you will see "select City" as title
Prompt is used to show title on dropdown popup not for default text.
If you want to select the default value on spinner
when you have not selected any value from spinner dropdown.
Then you must use
NothingSelectedSpinnerAdapter
How to make an Android Spinner with initial text "Select One"

Related

Spinner listener OnItemSelectedListener function without click on spinner

I have an activity Advanced Research, with a spinner that contains all category from my db. When i create the activity, this spinner call onSetItemListener in loop. Why?
I try to use onTouchListener but not working, maybe i fail something.
if(risultato.getCategoria().getSottocategorie().toArray() != null && risultato.getCategoria().getSottocategorie().toArray().length != 0){
adapterSpinnerCategoria = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, risultato.getCategoria().getSottocategorie().toArray());
}else{
adapterSpinnerCategoria = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, categoriaVuota);
}
spinnerCategoria.setAdapter(adapterSpinnerCategoria);
public void spinnerChange(AdapterView<?> parent){
if(!parent.getSelectedItem().toString().equals("Sottocategorie vuote")) {
ricercaAvanzata.setCategoria((Categoria) parent.getSelectedItem());
setArticoli();
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
spinnerChange(parent);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
return;
}
public void setListener() {
spinnerCategoria.setOnItemSelectedListener(this);
}
public class ActivityRicercaAvanzata extends AppCompatActivity implements AdapterView.OnItemSelectedListener { .... }
I expect that when i click on spinner call onItemSelected not before
i am using Spinner for Country Selection for User Registration.
please vote my answer.
Spinner spcountry;
String country;
//in onCreare
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
spcountry = (Spinner) findViewById(R.id.country);
final String[] countryNames = getResources().getStringArray(R.array.countries_array);
ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_spinner_item, countryNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spcountry.setAdapter(aa);
spcountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.v("item", (String) parent.getItemAtPosition(position));
if (position == 0) {
return;
} else
country = countryNames[position];
//Toast.makeText(getBaseContext(),country,Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
From what I can see, you are extending AdapterView.OnItemSelectedListener.
You cannot extend it since OnItemSelectedListener is an interface, not a class.
What you actually should be doing is, implementing it instead, like so:
MyActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
}
Then you can set the OnItemSelectedListener on the Spinner,
spinnerCategoria.setOnItemSelectedListener(this);
And the final step would be to write the implementation for the overridden methods,
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Your implementation here
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
//Your implementation here
}
Ok, mark as solved thx. I create a new List and i convert my set into list. After this operation i add a null element at first position, and when i'm call onItemSelected, i do
if(position != 0)then
//do something
Activity start always at position 0 then must wait my click and my choice. Thx all for help me.

How do I know the position of selected item in spinner?

I am inflating Spinner along with that I am also inflating some other views
LinearLayout child_linear = (LinearLayout) findViewById(R.id.child_linear);
LayoutInflater inflater = getLayoutInflater();
View myView = inflater.inflate(R.layout.add_custome_layout, child_linear, false);
name = (TextView) myView.findViewById(R.id.name);
price = (TextView) myView.findViewById(R.id.add_price);
names_spinner = (Spinner) myView.findViewById(R.id.product_addmore_spinner);
child_linear.addView(myView);
Now I getting data for the spinner. The question if there are 'n' no.of spinners how do I know which spinner item user selected?
names_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
parent.getItemAtPosition(position).toString();
if (parent.getItemAtPosition(position).toString().equalsIgnoreCase("Select Toppings")) {
//Show PopUp or Alerts
Toast.makeText(ProductView.this, "position" + names_spinner.getItemIdAtPosition
(position), Toast.LENGTH_SHORT).show(); }
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Even when I click on particular spinner item position is also not showing in Toast. What's my mistake?
You are showing toast only when user click on Select Toppings. Take a look to your code:
if (parent.getItemAtPosition(position).toString().equalsIgnoreCase("Select Toppings")) {
Change this line for
if (!parent.getItemAtPosition(position).toString().equalsIgnoreCase("Select Toppings")) {
And alerts should be shown.
Additionally to know which item is clicked, the listener provided you the clicked position, you can search in you items array this position and you can know which item is.
EDIT:
Now, lets suppose you have more than one spinner. spinner1 and spinner2, for example. You could register an OnItemSelectedListener for each one.
Then you can create a global variable called Spinner clickedSpinner and inside the OnItemSelectedListener of the spinner1 you set the clickedSpinner to spinner1 and inside the OnItemSelectedListener of the spinner2 set the clickedSpinner to spinner2:
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clickedSpinner = spinner1;
... // Do your stuff here
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
And:
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clickedSpinner = spinner2;
... // Do your stuff here
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
So, after clicking any item of any Spinner you can now know which Spinner was clicked because is stored in clickedSpinner.
Please note that this variable is not mandatory, you could achieve the same behavior without this global variable, because in each OnItemSelectedListener you know which spinner is the clicked. So, you could do the following:
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int spinner1Position = spinner1.getItemIdAtPosition(position);
... // Do your stuff here
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
And:
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int spinner2Position = spinner2.getItemIdAtPosition(position);
... // Do your stuff here
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Without using a global variable.
Hope this helps.
Try this
final Spinner names_spinner = (Spinner) myView.findViewById(R.id.product_addmore_spinner);
ArrayAdapter<String> madapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.yourarray));
madapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
names_spinner.setAdapter(madapter);
names_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String mySpinner = (String) adapterView.getItemAtPosition(i);
Log.i("names_spinner",mySpinner);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
Toast.makeText(getApplicationContext(),"Your Message",Toast.LENGTH_LONG).show();
}
});
}

how to get access to all items of a dynamically inflated layout in android

I dynamically inflate a view which contains spinner and edit text.how to understand which spinner listener is currently working.
count = 1;
buttonadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
Spinner spin_securityType = (Spinner) MyItem[count].findViewById(R.id.spin_securityType);
EditText ed_amount = (EditText) MyItem[count].findViewById(R.id.ed_amount);
SpinnerLogoAdapter spinnerAdapter33 = new SpinnerLogoAdapter(Activity.this.getApplicationContext(),
securityTpeIcons, securityTpeitems);
spin_securityType.setAdapter(spinnerAdapter33);
MainItemLayout.addView(MyItem[count]);
spin_securityType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView << ? > parent, View view, int position, long id) {
//how to know which spinner is selected ????????
}
#Override
public void onNothingSelected(AdapterView << ? > parent) {}
});
}
});
what i need is add a validation on one which validates all 5 items at a same time.I have tried setTag but it does not work.please help
I found the solution myself. I programatically added id for each spinner and access it inside the listener to know which spinner is selected.For that i added id to the spinner
spin_securityType.setId(id); ex:id=1
and access it inside spin_securityType.setOnItemSelectedListener()
spin_securityType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView parent, View view, int position, long id) {
int Id=parent.getId();//shows id as 1
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

ArrayList doesn't show up on Spinner

I was trying to create a spinner which display a list of data from array list.
When I clicked on the dropdown it displays the list, but when I clicked on an item inside the dropdown list it doesn't show up the value on the spinner.
Am I missing something here?
Note: Yesterday I have tried to check using Log.d() and System.out.println, itemOnSelected() doesn't but today it works fine. Maybe I rebuilding the project or I have changed something in the code but the value on the spinner still doesn't show up after I clicked on the item inside the spinner.
Spinner spnSubjectIDInfo;
ArrayList<String> subjectList;
ArrayAdapter<String> adpSubj;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
subjectList = new ArrayList<String>();
subjectList .add("John");
subjectList .add("Maxi");
subjectList .add("Jeni");
spnSubjectIDInfo = (Spinner) v.findViewById(R.id.spnSubjectIDInfo);
adpSubj = new ArrayAdapter<String>(MyActivity.this, android.R.layout.simple_spinner_item, subjectList);
adpSubj.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnSubjectIDInfo.setAdapter(adpSubj);
spnSubjectIDInfo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(this, parent.getItemAtPosition(position)+ " selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
XML
<Spinner
android:id="#+id/spnSubjectIDInfo"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:layout_marginTop="54dp"
android:layout_centerHorizontal="true" />
Try this
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(ActivityName.this, subjectList.get(position).toString() " selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
You are passing the wrong context to Toast instance:
If your code is in Activity then replace this by YourActivity.this or if it's in Fragment then use getActivity() or use Application context getApplicationContext(). Because currently, this is representing Spinner's onItemSelected listener context.
Do :
Toast.makeText(/*Your activity/application context*/, parent.getItemAtPosition(position)+ " selected", Toast.LENGTH_SHORT).show();
instead of:
Toast.makeText(this, parent.getItemAtPosition(position)+ " selected", Toast.LENGTH_SHORT).show();
Change the "this" to "ActvityName.this" or use "getApplicationContext()" in the Toast, you are passing anonymous class context in the toast.
Like below:
spnSubjectIDInfo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(ActivityName.this,parent.getItemAtPosition(position)+ " selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Hope this will help you.
public class SpinnerTest extends AppCompatActivity {
private ArrayList<String> subjectList;
private ArrayAdapter<String> adpSubj;
private Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_test);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
spinner= (Spinner) findViewById(R.id.spnSubjectIDInfo);
subjectList = new ArrayList<String>();
subjectList .add("John");
subjectList .add("Maxi");
subjectList .add("Jeni");
adpSubj = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, subjectList);
adpSubj.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adpSubj);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), spinner.getItemAtPosition(position).toString() + " selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
in Spinner setOnItemSelectedListener methord not work. if you want to get selected value show in toast use this line
String Text = mySpinner.getSelectedItem().toString();
Toast.makeText(this,Text,Toast.LENGTH_LONG).show();
it will return the selected value and will be displayed on Toast.
After few more searching I realized that I have to set the width size of the spinner to wrap_content as the length of the value doesn't support to display it on the spinner after the item being clicked at.
<Spinner
android:id="#+id/spnSubjectIDInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="54dp"
android:layout_centerHorizontal="true" />

Set spinner selected item text

I have a spinner (only relevant parts of code)...
protected void onCreate(Bundle savedInstanceState) {
Spinner to_spinner = (Spinner) findViewById(R.id.to_spinner);
List<Unit> list = myDbHelper.getAllUnits();
SpinnerUnitAdapter tUnitAdapter tUnitAdapter = new SpinnerUnitAdapter(this, android.R.layout.simple_spinner_item, list);
to_spinner.setAdapter(tUnitAdapter);
to_spinner.setOnItemSelectedListener(onItemSelectedListenerTo);
}
with an onItemSelectedListener
AdapterView.OnItemSelectedListener onItemSelectedListenerTo = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long id) {
// do stuff
}
#Override
public void onNothingSelected(AdapterView<?> adapter) {
}
};
When an item is selected (i.e. where it says: "do stuff"), I would like to set/change the text of the selected spinner item. (Note that this is not the same as setting the spinner position (with setSelection()).
I was thinking of doing this with
tUnitAdapter.getView(position, ?, ?).setText("new text");
Am I on the right track? What to put as second ("convertView") and third ("parent") argument in getView. My spinner adapter looks like:
public class SpinnerUnitAdapter extends ArrayAdapter<Unit> {
...
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView label = new TextView(mContext);
label.setTextColor(Color.BLACK);
label.setTextSize(mContext.getResources().getDimension(R.dimen.list_row_font_size));
label.setGravity(Gravity.CENTER);
label.setText(getItem(position).getName());
return label;
}
}
Am I on the right track?
No. You should do the following steps: (in the onItemSelected method)
Update your model (the array of items you passed to the adapter) so that the item at position index takes the new name.
Issue notifyDataSetChanged on the adapter object. Alternatively, you can do this manually by ((TextView) view).setText(new_name);
Note: In onItemSelected method, adapterView points to your spinner view and view points to the row view just selected.
UPDATE #1
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
((TextView) view).setText("new name");
}
UPDATE #2
For this, you should use Java interface to implement a callback which is called once the dialog is closed.
public void onItemSelected(AdapterView<?> adapterView, final View view, int position, long id) {
Dialog dialog = new MyDialog(context, new MyDialog.OnItemSelectListener(){
#Override
public void onItemSelected(String newName){
((TextView) view).setText(newName);
}
});
dialog.show();
}
And declare interface OnItemSelectListener in your MyDialog class.
You can change the text of spinner when you click each item so you should implement onClickListener
public class SpinnerUnitAdapter extends ArrayAdapter<Unit> {
...
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView label = new TextView(mContext);
...
label.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// change label text here
// label.setText(...);
}
});
return label;
}
}
Hope this help
I think I found the solution. I can just do:
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long id) {
TextView tv = (TextView) adapterView.getSelectedView();
tv.setText("new text");
}

Categories

Resources