• android 学习 Spinner控件的使用


      今晚看了下spinner控件的使用,结合博客大神的教程,一个小demo

    一,SpinnerActivity

     private Spinner spinner;
        private ArrayAdapter<String> adapter;
        private List<String> list;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_spinner);
            list = new ArrayList<String>();
            spinner = (Spinner)findViewById(R.id.spinner);
            initListData();
            adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
            adapter.setDropDownViewResource(R.layout.spinner_dropdownlayout);
            spinner.setAdapter(adapter);
            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    String add = adapter.getItem(position);
                    Toast.makeText(getBaseContext(),add,Toast.LENGTH_LONG).show();
                }
                @Override
                public void onNothingSelected(AdapterView<?> parent) {
    
                }
            });
        }

    spinner 在使用的时候和之前学习的listview  gridview 一样,都需要预先加载好数据,所以一样也要使用适配器进行绑定。demo就使用的简单的ArrayAdapter,显示一个字符串就可以说明问题了。使用的布局样式还是系统自带的  android.R.layout.simple_spinner_item 

    查看源码,布局也很简单,单行,滚动,还有就是设置文字的对齐方式

    simple_spinner_item.xml

    <TextView xmlns:android="http://schemas.android.com/apk/res/android" 
        android:id="@android:id/text1"
        style="?android:attr/spinnerItemStyle"
        android:singleLine="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ellipsize="marquee"
        android:textAlignment="inherit"/>

    还有一个地方需要注意,就是 setDropDownViewResource,该函数用来设置下拉菜单样式,在demo中用了下自定义的下拉样式,内部布局也是一个简单TextView,设置文字大小,文字颜色等属性。当然成功显示。

    如果没有设置下拉样式,那么该样式和spinner的样式是一样的。

    spinner有两种显示方式 一种是弹框,一种是下拉,可以通过属性设置。

    android:spinnerMode="dropdown"
    android:spinnerMode="dialog"
    spinner_dropdownlayout.xml
    <?xml version="1.0" encoding="utf-8"?>
    
    <TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textView5"
    android:layout_width="wrap_content"
    android:layout_height="24sp"
    android:singleLine="true"
    android:textColor="#045556"
    style="?android:attr/spinnerDropDownItemStyle" />

     如果需要显示图片,文字混排的样式,那么使用SimpleAdapter适配器,就跟上节一样,然后把下拉样式也设置成一样的。

  • 相关阅读:
    《那些年啊,那些事——一个程序员的奋斗史》——40
    《那些年啊,那些事——一个程序员的奋斗史》——41
    《那些年啊,那些事——一个程序员的奋斗史》——42
    《那些年啊,那些事——一个程序员的奋斗史》——40
    《那些年啊,那些事——一个程序员的奋斗史》——41
    《那些年啊,那些事——一个程序员的奋斗史》——42
    《那些年啊,那些事——一个程序员的奋斗史》——40
    箭牌卫浴(帮朋友发的广告贴)
    Playing with ptrace
    [open source]通过汉字得到拼音的函数库(getpinyin)发布
  • 原文地址:https://www.cnblogs.com/techdreaming/p/4937657.html
Copyright © 2020-2023  润新知