Android基础 - 下拉列表

文章目录标题

布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:layout_editor_absoluteX="0dp" tools:layout_editor_absoluteY="53dp" android:id="@+id/linearLayout">

        <!--    下拉列表    -->
        <Spinner
                android:layout_width="match_parent"
                android:layout_height="wrap_content" android:id="@+id/feature" android:entries="@array/feature"/>
        <Button
                android:text="@string/find"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" android:id="@+id/find" android:onClick="resq"/>
        <TextView
                android:text="@string/language"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" android:id="@+id/language"/>
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

响应

package com.test;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    
    

    private  final Select select= new Select();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /**
     * 响应button的onClick事件
     * 方法名和onClick的值一致
     */
    public void resq(View button){
    
    

        //通过id获取下拉列表
        Spinner spinner = findViewById(R.id.feature);

        //获取下拉列表里的文字
        String feature = spinner.getSelectedItem().toString();

        //通过id获取文本框
        TextView textView = findViewById(R.id.language);

        String language = select.get(feature);

        //显示文字
        textView.setText(language);
    }
}

模型层(java类)

package com.test;

public class Select {
    
    

    public String get(String feature){
    
    

        switch (feature){
    
    
            case "fast":return "c/c++";
            case "easy":return "python";
            case "new":return "java";
            case "00":return "00";
            default: return "you got me";

        }
    }
}

猜你喜欢

转载自blog.csdn.net/m0_46267375/article/details/108736462