res/values/strings.xml
1 2 3 4 5 6 7 8 9 10 |
<resources> <string name="app_name">JackApplication</string> <string-array name="country_arrays"> <item>Malaysia</item> <item>Indonesia</item> <item>Singapore</item> </string-array> </resources> |
บรรทัดที่ 4-8: เตียมข้อมูลไว้แสดงใน Spinner
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Spinner android:id="@+id/spinner" android:layout_width="fill_parent" android:layout_height="wrap_content" android:entries="@array/country_arrays" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout> |
บรรทัดที่ 14: ใส่ข้อมูล country_arrays
จากไฟล์ res/values/strings.xml เข้าไปให้ Spinner
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package com.phaisarn.jackapplication; 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); final Spinner spinner = findViewById(R.id.spinner); spinner.setSelection(1); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String text = spinner.getItemAtPosition(position).toString(); Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { //Toast.makeText(getApplicationContext(), "Nothing Selected", Toast.LENGTH_SHORT).show(); } }); } } |
บรรทัดที่ 17: ประกาศตัวแปร spinner
บรรทัดที่ 19: กำหนดค่าเริ่มต้นว่าให้เลือก item ที่ 1
บรรทัดที่ 24: อ่านค่า item ที่ถูกเลือก
Link