Basic use of spinner (list option box)


Introduction to this section:

Originally this section wanted to introduce you to a control of Gallery, but after thinking about it, I forgot about it because It has been deprecated after Android 4.1. Although we can use Gallery through compatibility, but think about it Forget it, because Gallery needs to re-create the view every time it switches pictures, which will undoubtedly cause What a waste of resources! We can achieve the Gallery effect through other methods, such as through HorizontalScrollView To achieve the horizontal scrolling effect, or write a horizontal ListView ~ Google it yourself if you are interested!

This section is about an Adapter control called Spinner! Application scenario: When our app requires users to input data, in addition to letting users type by themselves, there is also a more considerate design: Making it easier for our users by listing a set of options for them to choose from! Without further ado, let’s start learning the basic usage of Spinner~


1. Related attributes

  • android:dropDownHorizontalOffset: Set the horizontal offset distance of the list box
  • android:dropDownVerticalOffset:Set the horizontal and vertical distance of the list box
  • android:dropDownSelector:List box Background when selected
  • android:dropDownWidth: Set the width of the drop-down list box
  • android:gravity: Set the alignment of the components inside
  • android:popupBackground: Set the background of the list box
  • android:prompt: Set the prompt information (title) of the list box in dialog mode , can only reference string.xml The resource id in the resource id cannot be written directly as a string
  • android:spinnerMode: The mode of the list box, there are two optional values: dialog: Dialog style Window dropdown: Drop-down menu style window (default)
  • Optional attributes: android:entries: Use array resources to set the list items of the drop-down list box

2. Usage example:

By the way, Spinner will select the first value by default, which is to call spinner.setSection(0) by default, You can set the default selected value through this. In addition, OnItemSelectedListener will be triggered once. Event, no solution has been found yet. The following compromise is: add a boolean value, and then set If it is false, it will be judged when onItemSelected. If false, it means it is triggered by default and no operation will be performed. Set the boolean value to true; if true, the event will be triggered normally! In the example, two different Spinners are written to compare from the data source, list box style, etc.~ Next, let’s take a look at

Rendering:

1.gif

Code implementation:

Our previous reusable BaseAdapter is still used here:

The first Spinner data source preparation:

Write a file under res/values: myarrays.xml with the following content:

<?xml version="1.0" encoding="utf-8"?>
<resources>
; <string-array name="data">
; <item>Valiant Bronze</item>
; < ;item>Unyielding Silver</item>
                                                           < item>
                                                                     

##Then there is the layout of the second Spinner:
item_spin_hero.xml

##<?xml version="1.0" encoding="utf- 8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent" android:layout_height=" match_parent" android:orientation="horizontal"

android:padding="5dp">
<ImageView
android:id="@+id/img_icon"
android:layout_width="48dp"
android:layout_height="48dp"
android:src="@mipmap/iv_lol_icon1" />

<TextView
android:id=" @+id/txt_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>

再接着编写一个Entitiy实体类:Hero.java

/**
 * Created by Jay on 2015/9/24 0024.
 */
public class Hero {

    private int hIcon;
    private String hName;

    public Hero() {
    }

    public Hero(int hIcon, String hName) {
        this.hIcon = hIcon;
        this.hName = hName;
    }

    public int gethIcon() {
        return hIcon;
    }

    public String gethName() {
        return hName;
    }

    public void sethIcon(int hIcon) {
        this.hIcon = hIcon;
    }

    public void sethName(String hName) {
        this.hName = hName;
    }
}

最后是MainActivity的布局与Java代码部分:

布局文件:activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp"
    tools:context=".MainActivity">
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="选择您的排位分段"
        android:textColor="#44BDED"
        android:textSize="18sp" />

    <Spinner
        android:id="@+id/spin_one"
        android:layout_width="100dp"
        android:layout_height="64dp"
        android:entries="@array/data"
        android:prompt="@string/spin_title"
        android:spinnerMode="dialog" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="选择你的拿手英雄~"
        android:textColor="#F5684A"
        android:textSize="18sp" />

    <Spinner
        android:id="@+id/spin_two"
        android:layout_width="wrap_content"
        android:layout_height="64dp" />

</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    private Spinner spin_one;
    private Spinner spin_two;
    private Context mContext;
    //判断是否为刚进去时触发onItemSelected的标志
    private boolean one_selected = false;
    private boolean two_selected = false;
    private ArrayList<Hero> mData = null;
    private BaseAdapter myAdadpter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;
        mData = new ArrayList<Hero>();
        bindViews();
    }


    private void bindViews() {
        spin_one = (Spinner) findViewById(R.id.spin_one);
        spin_two = (Spinner) findViewById(R.id.spin_two);

        mData.add(new Hero(R.mipmap.iv_lol_icon1,"迅捷斥候:提莫(Teemo)"));
        mData.add(new Hero(R.mipmap.iv_lol_icon2,"诺克萨斯之手:德莱厄斯(Darius)"));
        mData.add(new Hero(R.mipmap.iv_lol_icon3,"无极剑圣:易(Yi)"));
        mData.add(new Hero(R.mipmap.iv_lol_icon4,"德莱厄斯:德莱文(Draven)"));
        mData.add(new Hero(R.mipmap.iv_lol_icon5,"德邦总管:赵信(XinZhao)"));
        mData.add(new Hero(R.mipmap.iv_lol_icon6,"狂战士:奥拉夫(Olaf)"));

        myAdadpter = new MyAdapter<Hero>(mData,R.layout.item_spin_hero) {
            @Override
            public void bindView(ViewHolder holder, Hero obj) {
                holder.setImageResource(R.id.img_icon,obj.gethIcon());
                holder.setText(R.id.txt_name, obj.gethName());
            }
        };
        spin_two.setAdapter(myAdadpter);
        spin_one.setOnItemSelectedListener(this);
        spin_two.setOnItemSelectedListener(this);

    }


    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()){
            case R.id.spin_one:
                if(one_selected){
                    Toast.makeText(mContext,"您的分段是~:" + parent.getItemAtPosition(position).toString(),
                            Toast.LENGTH_SHORT).show();
                }else one_selected = true;
                break;
            case R.id.spin_two:
                if(two_selected){
                    TextView txt_name = (TextView) view.findViewById(R.id.txt_name);
                    Toast.makeText(mContext,"您选择的英雄是~:" + txt_name.getText().toString(),
                            Toast.LENGTH_SHORT).show();
}else two_selected = true;
break;
}
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}
}

In addition, regarding Spinner’s OnItemSelectedListener and how to get the value of the selected item, just read the above. Code~


3. Code sample download:

SpinnerDemo.zip


Summary of this section

Okay , this section introduces you to the use of Spinner (drop-down option box), the example is quite interesting, haha~! Don't ask me which zone or rank I am, I am the little prince of man and machine, but unfortunately I have been struggling in the bronze rank~ You know why2.gif, okay, that’s it for this section~