瘋狂 Android 講義, 4/e – 下拉式選單(Spinner & TextView & AdapterView)範例 P120~P121

瘋狂 Android 講義, 4/e – 下拉式選單(Spinner & TextView & AdapterView)範例 P120~P121

瘋狂 Android 講義, 4/e – 下拉式選單(Spinner & TextView & AdapterView)範例 P120~P121



資料來源:

    https://github.com/daichangya/book/tree/master/android
    https://pan.baidu.com/s/1d_xYJI0UQ_1tQzSj_V_NIg 提取码:70ch
    https://hjwang520.pixnet.net/blog/post/405000676-%5Bandroid-studio%5D%E4%B8%8B%E6%8B%89%E5%BC%8F%E9%81%B8%E5%96%AE%28spinner%29%E7%AD%86%E8%A8%98



XML Code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!-- 定义了一个Spinner组件-->
    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />
</LinearLayout>



Java Code

package com.example.as_test01;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import android.widget.AdapterView;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    private TextView textView;
    // 定义一个数组
    public String[] arr = new String[]{"孙悟空", "猪八戒", "唐僧"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.textView);

        // 获取界面布局文件中的Spinner组件
        Spinner spinner = findViewById(R.id.spinner);
        String[] arr = new String[]{"孙悟空", "猪八戒", "唐僧"};
        // 创建ArrayAdapter对象
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, arr);//android.R.layout.simple_list_item_multiple_choice
        // 为Spinner设置Adapter
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(spnOnItemSelected);

        textView.setText("選項:"+spinner.getSelectedItem().toString());
    }

    private AdapterView.OnItemSelectedListener spnOnItemSelected = new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view,
                                   int pos, long id) {
            String sPos=String.valueOf(pos);
            String sInfo=parent.getItemAtPosition(pos).toString();
            //String sInfo=parent.getSelectedItem().toString();
            textView.setText("選項"+sPos+":"+sInfo);
        }
        public void onNothingSelected(AdapterView<?> parent) {
            //
        }
    };

}

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *