i dont understand what is meant by R.layout or R.array in the following code, who describes how to fill a spinner with drop-down menue with a array who has different countries as its elements:
adapter = ArrayAdapter.createFromResource(this, R.array.countries, androidx.appcompat.R.layout.support_simple_spinner_dropdown_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinnerCountry.setAdapter(adapter);
The string Array with the name "countries" is loacated in the strings.xml file, in folder res -> values. Why is it necessary to use R.array to locate the country array and why can i not use findViewbyID? And second question is why is in R.layout the spinner called support_simple_spinner_dropdown_item? If i choose spinner on the Design tab via drag and drop theres only one spinner to choose.
Would be nice to have some help. Thank you.
I looked on the Developersite and searched the forum.
CodePudding user response:
First, the values under R
are generated at compile time. They're simply a list of int
values with names likes R.array.<name>
or R.id.<name>
that can be used as identifiers for actual arrays, views, or whatever.
I think the official docs explain what is happening quite well, but I'll explain in my own words anyway.
Why is it necessary to use R.array to locate the country array and why can i not use findViewbyID?
A string array is not a View
, so it wouldn't make sense to use findViewById
. findViewById
is a method that returns the View
referenced by an int
value defined in the R.id
constants.
R.array.countries
will just be an int
value that references a string array. To get the String[]
for that id, you would instead use Resources::getStringArray(...)
. So, in the context of an Activity, you'd do final String[] array = getResources().getStringArray(R.array.countries);
.
why is in R.layout the spinner called support_simple_spinner_dropdown_item
support_simple_spinner_dropdown_item
is the id for a layout. You should understand some of the different components of a spinner. There is:
- The
View
itself. There is only one of these, and it's what you see in the drag-and-drop option in the design/laout editor. - The layout id for each row in the spinner when it is open. This is defined in the
layout
xml file referenced byR.layout.simple_spinner_item
. - The data used to populate each row. This is defined in the array referenced by
R.array.countries
.