Scenes
Achieve results as follows
Note:
Blog:
https://blog.csdn.net/badao_liumang_qizhi
public concern number of
programs overbearing ape
acquisition-related programming e-books, tutorials and push for free download.
achieve
To the LinearLayout layout, and by android: orientation = "vertical"> vertical layout setting, and then add the id attribute.
Then New arrays.xml, an array of resources in the file under res values, used to store the contents of the drop-down box options
arrays.xml:
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="ctype"> <item>全部</item> <item>公众号</item> <item>霸道</item> <item>的</item> <item>程序猿</item> <item>博客</item> <item>霸道</item> <item>流氓</item> <item>气质</item> </string-array> </resources>
只要通过name属性赋值为ctype,后续被引用。
然后再回到activity_spinner.xml中,通过
android:entries="@array/ctype"
为下拉框设置选项数组内容。
activity_spinner.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:orientation="horizontal" tools:context=".SpinnerActivity"> <Spinner android:id="@+id/spinnner" android:entries="@array/ctype" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
然后来到activity,通过id获取spinner,然后设置其选项被选中的事件监听器,获取选中值的内容并输出
package com.badao.relativelayouttest; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.Spinner; import android.widget.Toast; public class SpinnerActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_spinner); Spinner spinner = (Spinner) findViewById(R.id.spinnner); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String result = parent.getItemAtPosition(position).toString(); Toast.makeText(SpinnerActivity.this,result,Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } }