Basic use of Spinner

Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

When our app requires user input, in addition to letting users type their own data, there is a thoughtful design that makes it easier for our users to choose from a list of options!

Spinner a total of two components, one is itself the Spinner, one is android. Support. V7. Widget. AppCompatSpinner The difference between the two is that the Spinner in V7 is compatible with the lower version, the Spinner can be used in the higher version until 2.1 (V7 is compatible with API7), there is no other difference between the use of the two except the first time

1. Common attributes

The property name role
android:dropDownHorizontalOffset Sets the horizontal offset of the list box
android:dropDownVerticalOffset Set the horizontal and vertical distance of the list box
android:dropDownSelector The background when the list box is selected
android:dropDownWidth Set the width of the drop-down list box –
android:gravity Sets how components inside are treated
android:popupBackground Sets the background of the list box
android:prompt The prompt (title) for the listbox that sets the dialog mode can only reference the resource ID in String.xml, not write a string directly
android:spinnerMode Dropdown: a dropdown menu style window (default)
Optional property: Android: Entries Use array resources to set the list items in the drop-down list box

Two, the use of steps

Three, the instance,

Project Structure:

  1. Create arrays.xml in the values folder to store the array

      
<resources>
    <string-array name="data">
        <item>Stubborn bronze</item>
        <item>Order of the silver</item>
        <item>The glory of gold</item>
        <item>Honorable platinum</item>
        <item>Eternal diamond</item>
        <item>The ultimate star yao</item>
        <item>Most of the king</item>
        <item>The glory of the king</item>
    </string-array>
</resources>
Copy the code
  1. Writing layout files

      
<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"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:gravity="center">

   <ImageView
       android:layout_width="fill_parent"
       android:layout_height="100dp"
      android:src="@drawable/bg"/>
   <TextView
       android:layout_marginTop="20dp"
       android:layout_width="200dp"
       android:layout_height="wrap_content"
       android:text="Select your rank segment"
       android:textColor="#44BDED"
       android:textSize="18sp" />

   <Spinner
       android:id="@+id/spinner_rank"
       android:layout_width="220dp"
       android:layout_height="64dp"
       android:entries="@array/data"
       android:prompt="@string/title"
       android:spinnerMode="dialog" />

   <TextView
       android:textStyle="bold"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_marginTop="10dp"
       android:text="Choose your hero."
       android:textColor="#F5684A"
       android:textSize="18sp" />

   <Spinner
       android:id="@+id/spinner_hero"
       android:layout_width="match_parent"
       android:layout_height="64dp" />


   <LinearLayout
       android:layout_marginTop="30dp"
       android:layout_width="wrap_content"
       android:layout_height="40dp"
       android:gravity="center_vertical">
      <TextView
          android:textSize="20sp"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="What's your segment?"/>
      <TextView
          android:textSize="20sp"
          android:id="@+id/rank"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Stubborn bronze"/>
   </LinearLayout>
   <LinearLayout
       android:layout_width="wrap_content"
       android:layout_height="50dp"
       android:gravity="center_vertical">
      <TextView
          android:textSize="20sp"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="What heroes are you good at?"/>
      <TextView
          android:id="@+id/hero"
          android:textSize="20sp"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Arthur"/>
      <ImageView
          android:id="@+id/im_hero"
          android:layout_width="48dp"
          android:layout_height="48dp"
         android:src="@drawable/yase"/>
   </LinearLayout>
</LinearLayout>
Copy the code
  1. Write the entity class HeroBean to dynamically inject the name and image of our selected hero
package com.mq.spinner;

public class HeroBean {
    private int icon;
    private String name;

    public HeroBean(a) {}public HeroBean(int icon, String name) {
        this.icon = icon;
        this.name = name;
    }

    public int getIcon(a) {
        return icon;
    }

    public String getName(a) {
        return name;
    }

    public void setIcon(int icon) {
        this.icon = icon;
    }

    public void seName(String name) {
        this.name = name; }}Copy the code
  1. Add a layout of Spinner items and name it spinner_item.xml

      
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp">


    <ImageView
        android:id="@+id/icon"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:src="@drawable/yase"/>

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="15dp"
        android:text="Demacia"
        android:textSize="16sp" />
</LinearLayout>
Copy the code
  1. Write a MyAdapter adapter that lets the Spinner return the selected view

Spinner inherits from AdapterView, which means it also provides data support through Adapter

Spinner selects the first value by default, which is the default call to Spinner. SetSection (0), which we also use to set the default value

package com.mq.spinner;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class MyAdapter extends BaseAdapter {
    private List<HeroBean> mHeroBeans;
    private Context mContext;

    public MyAdapter(List<HeroBean> heroBeans, Context context) {
        this.mHeroBeans = heroBeans;
        this.mContext = context;
    }

    @Override
    public int getCount(a) {
        return mHeroBeans.size();
    }

    @Override
    public Object getItem(int i) {
        return mHeroBeans.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        LayoutInflater _LayoutInflater=LayoutInflater.from(mContext);
        view=_LayoutInflater.inflate(R.layout.spinner_item, null);
        if(view! =null)
        {
            TextView textView=(TextView)view.findViewById(R.id.name);
            ImageView imageView=view.findViewById(R.id.icon);
            textView.setText(mHeroBeans.get(position).getName());
            imageView.setImageResource(mHeroBeans.get(position).getIcon());
        }
        returnview; }} pieceCopy the code
  1. Write MainActivity code, annotated code
public class MainActivity extends AppCompatActivity {

    private Spinner scope;
    private Spinner hero;
    private TextView t_rank,t_hero;
    private ImageView m_hero;
    
    private ArrayList<HeroBean> mData = null;// An array of hero names and images
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView(a) {

        scope=findViewById(R.id.spinner_rank);
        hero=findViewById(R.id.spinner_hero);
        t_hero=findViewById(R.id.hero);
        t_rank=findViewById(R.id.rank);
        m_hero=findViewById(R.id.im_hero);

        mData=new ArrayList<HeroBean>();

        mData.add(new HeroBean(R.drawable.sunwukong,"Sun Wukong"));
        mData.add(new HeroBean(R.drawable.zixia,"Purple Glow Fairy"));
        mData.add(new HeroBean(R.drawable.diaocan,"The sable cicada"));
        mData.add(new HeroBean(R.drawable.hanxin,"Han xin"));
        mData.add(new HeroBean(R.drawable.machao,"D"));
        mData.add(new HeroBean(R.drawable.bailixuance,A hundred miles of secrets.));

        MyAdapter adapter = new MyAdapter(mData, this);// Instantiate the adapter

        hero.setAdapter(adapter);// Set the adapter for Hero

        // Add a listener to the spinner of the selected segment
        scope.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<? > adapterView, View view,int i, long l) {
                t_rank.setText(scope.getSelectedItem().toString());
            }

            @Override
            public void onNothingSelected(AdapterView
        adapterView) {}});// Add a listener to the spinner that selects the hero
        hero.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override // The method to execute when selected
            public void onItemSelected(AdapterView<? > adapterView, View view,int i, long l) {
                Toast.makeText(MainActivity.this, mData.get(i).getName(), Toast.LENGTH_SHORT).show();
                t_hero.setText(mData.get(i).getName());// Set the selected hero name on the TextView
                m_hero.setImageResource(mData.get(i).getIcon());// Give the selected hero image to Imageview
            }

            @Override
            public void onNothingSelected(AdapterView
        adapterView) {}}); }}Copy the code

summary

  • Spinner will select the first value by default, which is the default call to Spinner. SetSection (0), which you can use to set the default selected value
  • An OnItemSelectedListener event is raised. Add a Boolean and set it to false. Check onItemSelected. False means the Boolean is triggered by default. True triggers the event normally!
  • There are two ways to load a data source:
    • By XML loading, the first selection segment in the instance is loaded using XML, byandroid:entries
    • Load the data source with code. The second option in this example is to load the data source with code, using an Array, etc.
    • XML is characterized by convenience and speed, but the disadvantage is that the data to be displayed cannot be dynamically changed. The use of adapters is characterized by flexibility and choice according to the needs of the project.
  • Android: FAQ about using the prompt property

No effect: Prompt is only useful in dialog state, so in XML, set the style to widget. Spinner prompt uses string resources and does not support character input directly, otherwise an error will be reported

  • Spinner displays menus in two waysBoth are used in the example
    • Pop-up box form, via propertiesandroid:spinnerMode="dialog" Set up the
    • Drop – down box form through propertiesandroid:spinnerMode="dropdown"Set, default is drop down box

Give it a thumbs up when you see the end!