Try Load with Spinner string-array from resources xml
To define string-array in resources xml, edit values/strings.xml to add items of string-array.
1 2 3 4 5 6 7 8 9 10 11 12 | <resources> <string name="app_name">AndroidSpinner</string> <string-array name="weekday"> <item>Sunday</item> <item>Monday</item> <item>Tuesday</item> <item>Wednesday</item> <item>Thursday</item> <item>Friday</item> <item>Saturday</item> </string-array> </resources> |
Edit layout/activity_main.xml to add Spinner with entries to load from string-array.
1 2 3 4 5 6 7 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:orientation="vertical" tools:context="com.example.androidspinner.MainActivity"> |
<TextView
android:id=”@+id/title”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”android-coding.blogspot.com”
android:textSize=”28dp”
android:textStyle=”bold” />
<Spinner
android:id=”@+id/myspinner”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:entries=”@array/weekday”/>
</LinearLayout>
1 |
MainActivity.java
1 | package com.example.androidspinner; |
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner mySpinner = (Spinner)findViewById(R.id.myspinner);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String item = (String)adapterView.getItemAtPosition(i);
Toast.makeText(MainActivity.this, item, Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
1 |