A data source of a Spinner can be data fetched from a local SQLite or a remote Mysql database, an array of strings, an ArrayList object, or an string array defined in xml layout file. In this Android tip, I am going to show to how to define a string array in xml file and how to read items of the array to display in a Spinner widget.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">AndApp</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string-array name="array_countries">
<item>Australia</item>
<item>Canada</item>
<item>Cambodia</item>
<item>China</item>
<item>England</item>
<item>France</item>
<item>Japan</item>
<item>Rusia</item>
<item>USA</item>
</string-array>
</resources>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.myfirstprogram.MainActivity" >
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="5sp"
android:paddingBottom="10sp"
android:paddingTop="10sp"
>
</TextView>
</RelativeLayout>
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner=(Spinner)findViewById(R.id.spinner);
String[] countries=getResources().getStringArray(R.array.array_countries);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.text, countries);
spinner.setAdapter(adapter);
}
|
This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.