自定义下拉控件,recyclerview中使用下拉控件

728 阅读3分钟

Myspinner

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import kotlinx.android.synthetic.main.myspinner.view.*
import java.util.*

class Myspinner : LinearLayout {
    private var popupWindow: PopupWindow? = null
    var dataList: List<String> =
        ArrayList()
    var maplist = mutableListOf<MutableMap<String, String>>()
    var nowchoose = ""
    var nowmap = mutableMapOf<String, String>()
    private var width1 = 0
    private var itemListener: OnClickListener? = null
    private var text: String? = null

    constructor(context: Context?) : super(context)
    constructor(
        context: Context?,
        attrs: AttributeSet?
    ) : super(context, attrs) {
        LayoutInflater.from(context).inflate(R.layout.myspinner, this, true)
        setOnClickListener {
            if (popupWindow == null) {
                showPopWindow()
            } else {
                closePopWindow()
            }
        }
    }

    //打开下拉列表弹窗
    private fun showPopWindow() {
        // 加载popupWindow的布局文件
        val contentView =
            LayoutInflater.from(context).inflate(R.layout.myspinner_list, null, false)
        val listView = contentView.findViewById<ListView>(R.id.listView)
        listView.layoutParams.let {
            if (width1 > 0) {
                it.width = width1
            }
        }
        listView.adapter = MyspinnerAdapter(context, dataList, maplist)
        popupWindow = PopupWindow(
            contentView,
            LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT
        ).apply {
            setBackgroundDrawable(resources.getDrawable(R.color.transparent, null))
            isOutsideTouchable = true
            showAsDropDown(this@Myspinner)
        }

    }

    fun setListViewWidth(width: Int) {
//       this.width=dip2px(context,width+30);//加上下拉图片的30dp
        this.width1 = width
    }

    //关闭下拉列表弹窗
    fun closePopWindow() {
        popupWindow!!.dismiss()
        popupWindow = null
    }

    //设置数据
    fun setItemsData(list: MutableList<String>) {
        dataList = list
        if (list.isNotEmpty()) {
            mysp_text.text = list[0]
            nowchoose = list[0]
        }
    }

    //设置map数据
    fun setItemsmapData(maplist: MutableList<MutableMap<String, String>>) {
        this.maplist = maplist
        val toList = maplist.map { it.values.toString().replace("[", "").replace("]", "") }
        dataList = toList
        if (toList.isNotEmpty()) {
            mysp_text.text = toList[0].toString()
            nowchoose = toList[0].toString()
            nowmap = maplist[0]
        }
    }

    //数据适配器
    internal inner class MyspinnerAdapter(
        var mContext: Context,
        var mData: List<String>,
        var maplist: MutableList<MutableMap<String, String>>
    ) : BaseAdapter() {
        var inflater: LayoutInflater = LayoutInflater.from(mContext)

        init {
            if (mData.isNotEmpty()) {
                nowchoose = mData[0] //默认选中第一个
                if (maplist.isNotEmpty()) {
                    nowmap = maplist[0]
                }
            }
        }

        override fun getCount(): Int {
            //  Auto-generated method stub
            return mData.size
        }

        override fun getItem(position: Int): Any? {
            //  Auto-generated method stub
            return null
        }

        override fun getItemId(position: Int): Long {
            //  Auto-generated method stub
            return position.toLong()
        }

        override fun getView(
            position: Int,
            convertView: View?,
            parent: ViewGroup
        ): View? {
            //  Auto-generated method stub
            // 自定义视图
            var convertView = convertView
            var listItemView: ListItemView? = null
            if (convertView == null) {
                // 获取list_item布局文件的视图
                convertView = inflater.inflate(R.layout.myspinner_list_item, null)
                listItemView = ListItemView()
                // 获取控件对象
                listItemView.tv = convertView.findViewById<View>(R.id.tv) as TextView
                listItemView.layout =
                    convertView.findViewById<View>(R.id.item) as LinearLayout
                // 设置控件集到convertView
                convertView.tag = listItemView
            } else {
                listItemView = convertView.tag as ListItemView
            }

            // 设置数据
            listItemView.tv!!.text = mData[position]
            text = mData[position]
            listItemView!!.layout!!.setOnTouchListener { view, motionEvent ->
                mysp_text!!.text = mData[position]
                nowchoose = mData[position]
                if (maplist.isNotEmpty()) {
                    nowmap = maplist[position]
                }
                false
            }
            if (itemListener != null) {
                listItemView.layout!!.setOnClickListener(itemListener)
            } else {
                listItemView.layout!!.setOnClickListener {
                    //关闭下拉列表
                    closePopWindow() //这一句执行onclick就不能执行
                }
            }
            return convertView
        }

    }

    /**
     * 设置点击监听事件
     * 调用此事件的时候需要加上 xcd.closePopWindow();//关闭弹窗
     * @param listener
     */
    fun setItemListener(listener: OnClickListener?) {
        itemListener = listener
    }

    //设置当前选中
    fun setNowChoose(text: String) {
        mysp_text!!.text = text
        nowchoose = text
    }

    private class ListItemView {
        var tv: TextView? = null
        var layout: LinearLayout? = null
    }

    fun getNowChoose(): String {
        return nowchoose
    }

    fun setNowmap1(map1: MutableMap<String, String>) {
        mysp_text!!.text = map1.values.toString().replace("[", "").replace("]", "")
        nowmap = map1
    }

    fun getNOwmap1(): MutableMap<String, String> {
        return nowmap
    }
}

myspinner.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/compound"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/spinner_ripple_bg"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/mysp_text"
        android:layout_width="0dp"
        android:layout_height="24dp"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:padding="2dp"
        android:paddingLeft="10dp"
        android:singleLine="true"
        android:text=""
        android:textSize="12sp" />

    <ImageView
        android:id="@+id/btn"
        android:layout_width="30dp"
        android:layout_height="24dp"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/text"
        android:gravity="center"
        android:padding="2dp"
        android:src="@mipmap/up" />
</LinearLayout>

myspinner_list

<?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="vertical">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="@color/white"/>

</LinearLayout>

myspinner_list_item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/item"
    android:paddingTop="2dp"
    android:paddingBottom="2dp"
    android:layout_width="match_parent"
    android:background="@drawable/spinner_ripple_bg"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/tv"
        android:text="ddd"
        android:padding="2dp"
        android:textSize="12sp"
        android:textColor="#666"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

spinner_ripple_bg

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:color="#dedede"
    tools:ignore="NewApi">
    <item android:drawable="@drawable/spinner_normal" />
</ripple>

spinner_normal

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 矩形的填充色 -->
    <solid android:color="@color/white" />

    <stroke
        android:width="0.5dp"
        android:color="@color/color_dedede" />
    <padding/>
</shape>

使用

val maplist = mutableListOf(
            mutableMapOf(Pair("01", "仓库一")),
            mutableMapOf(Pair("02", "仓库一")),
            mutableMapOf(Pair("03", "仓库二"))
        )
//        val setTypeList = map.values
        myspinner.apply {
            post { this.setListViewWidth(this.width) }
            setItemsmapData(maplist)
            Log.i("result-->1", "设置后默认的nowmap${myspinner.nowmap}")
            Log.i(
                "result-->1",
                "设置后默认的nowmap的key是多少:${myspinner.nowmap.keys.toString()
                    .replace("[", "").replace("]", "")}"
            )
            setItemListener(View.OnClickListener {
                Log.i("result-->1", "setItemListener nowchoose${myspinner.nowchoose}")
                Log.i("result-->1", "setItemListener nowmap${myspinner.nowmap}")
//                mysp_now = nowchoose
                closePopWindow() //关闭下拉
            })
        }
recyclerview中:

myspinner.apply {
                        val setTypeList = mutableListOf("是", "否")
                        val setTypeList1 = mutableListOf("否", "是")
                        post { this.setListViewWidth(this.width) }
                        if ((data[position] as SelectInvDetailList.Data.Record)?.hege == "否") {
                            setItemsData(setTypeList1)
                        } else {
                            setItemsData(setTypeList)
                        }
                        setItemListener(View.OnClickListener {
                            Log.i("result-->data", "触发了几次nowchoose:${nowchoose}")
                            (data[position] as SelectInvDetailList.Data.Record).hege = nowchoose
                            closePopWindow() //关闭下拉
                            notifyDataSetChanged()
                        })
                    }