I've googled the way to set initial text for spinner widget such as here and elsewhere but I haven't found any solution that use less memory, less line of code.
So, Is there any alternative way to do this "clean" ?
Asked
Active
Viewed 25 times
-1

doliolarzz
- 45
- 1
- 8
-
2It is good practice and it is encouraged! I'm not the downvoter, but I think the downvote is motivated by the fact that you haven't created a "real" question. You should do that so other people could answer your question too, and because future readers might not even notice that you answered you own question & get confused. – Ronan Boiteau Jul 28 '18 at 20:41
-
@RonanBoiteau Edited the question, Thank you :) – doliolarzz Jul 28 '18 at 20:45
-
1You're welcome! Also, you should define "clean". Is it less lines of code? Code that's easier to understand? Faster code? Code that uses less memory? – Ronan Boiteau Jul 28 '18 at 20:48
1 Answers
1
The code:
List<String> data = new ArrayList<>();
data.add("a");
data.add("b");
data.add("c");
data.add("d");
Spinner spinner = findViewById(R.id.spinner);
ArrayAdapter<String> stringListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, data) {
@Nullable
@Override
public String getItem(int position) {
if(position == getCount())
return "Please Select One";
else
return super.getItem(position);
}
};
stringListAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(stringListAdapter);
spinner.setSelection(data.size());
The XML:
<Spinner
android:id="@+id/spinner"
android:layout_width="200dp"
android:layout_height="50dp"/>

doliolarzz
- 45
- 1
- 8