Android Spinner - how to resize selected item?

It looks like the counter is the size of the longest element specified in its adapter. This is good behavior for most cases, but in my particular case this is undesirable.

Is it possible to disable this? I think not by looking at Spinner.onMeasure () in the source, but decided that I would ask.

+4
source share
3 answers

I have achieved this now by subclassing Spinner:

public class SpinnerWrapContent extends IcsSpinner { private boolean inOnMeasure; protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { inOnMeasure = true; super.onMeasure(widthMeasureSpec, heightMeasureSpec); inOnMeasure = false; } public boolean isInOnMeasure() { return inOnMeasure; } } 

Then in my SpinnerAdapter getView () I used the selected position if I called from onMeasure ():

  public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView != null) view = convertView; else { int fixedPosition = (spinner.isInOnMeasure() ? spinner.getSelectedItemPosition() : position); // Here create view for fixedPosition } return view; } 
+4
source

It worked for me. The important part of this. Put the code below into your adapter and use selectedItemPosition to select text from an array of objects.

 int selectedItemPosition = position; if (parent instanceof AdapterView) { selectedItemPosition = ((AdapterView) parent) .getSelectedItemPosition(); } 

An example is given below.

 public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = getLayoutInflater(); final View spinnerCell; if (convertView == null) { // if it not recycled, inflate it from layout spinnerCell = inflater.inflate(R.layout.layout_spinner_cell, parent, false); } else { spinnerCell = convertView; } int selectedItemPosition = position; if (parent instanceof AdapterView) { selectedItemPosition = ((AdapterView) parent) .getSelectedItemPosition(); } TextView title = (TextView) spinnerCell.findViewById(R.id.spinnerTitle); title.setText(titles[selectedItemPosition]); return spinnerCell; } 

If you need an explanation, follow this link: http://coding-thoughts.blogspot.in/2013/11/help-my-spinner-is-too-wide.html

+1
source

If you just want to make Spinner shorter, this is easy to fix.

As a rule, you can change the height and width of any kind, giving it weight, or setting its layout_width and layout_height:

 <Spinner android:id="@+id/shortenedSpinner" android:layout_width="100dp" android:layout_height="50dp" /> 

This will make the counter shorter.

If you want the drop-down view to be shorter, this is different. In this case, I suppose you could provide a custom string in the getDropDownView () method of the spinner adapter, which has the same changes as above.

0
source

Source: https://habr.com/ru/post/1443356/


All Articles