android spinner 自定义view 和属性

需求说明:

例子:当我使用spinner,显示的内容并不是我要的,大致是id对应text,text用于展示,id用于和后台交互所以就需要自定义属性
PS:我只是举例子!不要和我较真!扛精们!

1.自定义好需要的属性信息

res》values》attrs.XML(没有创建一个XML)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--下拉列表的选中的条目id属性-->
    <declare-styleable name="SpinnerView">
        <attr name="selectId" format="integer"/>
    </declare-styleable>
</resources>
2.自定义一个view去继承spinner(其他的可扩展的控件和自定义的都可以这样使用
public class SpinnerView extends android.support.v7.widget.AppCompatSpinner {
    private int selectId;
    public SpinnerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //关联自定义属性
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.SpinnerView);
                //获得自定义属性的值,用于使用(我在这里只有读写这两个作用)
        selectId = a.getInt(R.styleable.SpinnerView_selectId,-1);
    }

    @Override
    public int getId() {
        return selectId;
    }

    @Override
    public void setId(int id) {
        this.selectId = id;
    }
}
3.在布局文件中声明自定义属性
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"//我说的就是这里
    android:layout_width="match_parent"
    android:layout_height="match_parent"
>
<路径.views.SpinnerView
  	   android:id="@+id/s_inspector_spinner"
       android:layout_width="match_parent"
       android:layout_height="60dp"
       app:selectId=""//这个就是自定义的属性了>

</路径.views.SpinnerView>

</android.support.constraint.ConstraintLayout>
4.在代码中读写该属性
spinnerView = findViewById(R.id.s_inspector_spinner);
int id = spinnerView.getSelectId();
 spinnerView.setSelectId(1);
5.有人让我把adapter写出来
public class SpinnerAdapter extends ArrayAdapter {

    private  List<SelectOptions> mdata = new ArrayList<>();
    private Context mContext;
    public SpinnerAdapter(@NonNull Context context, List<SelectOptions> mdata) {
        super(context, R.layout.item_spinner);
        this.mdata=mdata;
        this.mContext=context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //节省资源
        if(convertView==null){
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_spinner, null);
        }
        //将数据填入
        TextView textView =convertView.findViewById(R.id.item_spinner_text);
        SelectOptions item  = mdata.get(position);
        textView.setText(item.getText());
        return convertView;
    };

    @Override
    public String getItem(int position){
        return mdata.get(position).getText();
    }

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

猜你喜欢

转载自blog.csdn.net/zhaohan___/article/details/87706157