The solution is as follows. In the data we create the last item with the inscription, which should be in a closed spinner (in the example, this is select city .. ). Position in the spinner translate this point. Now in our closed state everything is displayed as it should.
MainActivity ^
public class MainActivity extends AppCompatActivity { Spinner spinner; private String[] city = { "Moscow", "New York", "Berlin", "Select city .." }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); spinner = (Spinner)findViewById(R.id.spinner); CustomAdapter adapter = new CustomAdapter(this, android.R.layout.simple_spinner_item, city); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setSelection(city.length - 1); } }
Now, to hide this item when expanding the list, simply reduce the item count in the adapter by one by overriding the getCount() method
CustomAdapter:
public class CustomAdapter extends ArrayAdapter { String [] city; public CustomAdapter(Context context, int resourceId, String[] city) { super(context, resourceId, city); this.city = city; } @Override public int getCount() { return city.length - 1; } }
You can also hide the first item, but this does not have to be done, since such a decision will complicate the logic, which is due to the fact that there will be a discrepancy between the list positions and the positions in the spinner, because although the item is hidden, it remains an index.
That is, it turns out that for the position of the city[1] data, the spinner will return position = 0 . When placing the starting point at the end of the list, we avoid this problem. In addition, the solution is much simpler and requires much less code.