【问题标题】:Bind AutoComplete Text View in MVVM在 MVVM 中绑定自动完成文本视图
【发布时间】:2020-01-19 03:51:49
【问题描述】:

我希望将 MVVM 模式中的自动完成文本视图与自定义适配器绑定,但不确定如何正确执行。我尝试使用 BindingAdapter 进行绑定,就像绑定微调器一样,但过滤器出现错误。它抛出了一个非法的参数异常。我想我没有正确设置绑定适配器。任何帮助将不胜感激。

<androidx.appcompat.widget.AppCompatAutoCompleteTextView
                    android:id="@+id/customerNameTextInputLayout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/customer_name"
                    android:imeOptions="actionSearch"
                    android:inputType="textAutoComplete|textAutoCorrect"
                    android:text="@={addSaleViewModel._customerName}"
                    android:selectedItemPosition="@={addSaleViewModel.selectedAutoComplete}"
                    app:partyAutoCompleteAdapter="@{addSaleViewModel.partyList}" />

这是我的适配器代码

class PartyAutoCompleteAdapter(private var items: ArrayList<AddPartyRequest>?) :
    BaseAdapter(), PartyListItemViewModel.PartyListItemViewModelListener, Filterable {

    private var listFilter: ListFilter? = null
    private var dataListAllItems: ArrayList<AddPartyRequest> = ArrayList()

    override fun getCount(): Int = items!!.size

    override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
        return getView(position, convertView, parent)
    }

    override fun getItem(position: Int) = items?.get(position)

    override fun getItemId(position: Int) = items!!.get(position).partyId.toLong()

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {

        lateinit var partyHolder: PartyAutoCompleteHolder

        if (convertView == null) {
            val binding: RowPartyItemViewBinding = DataBindingUtil.inflate(
                LayoutInflater.from(parent.context),
                R.layout.row_party_item_view,
                parent,
                false
            )

            partyHolder = PartyAutoCompleteHolder(binding)
            partyHolder.view.tag = partyHolder
            binding.partyItemViewModel = PartyListItemViewModel(position, items?.get(position), this)
            binding.executePendingBindings()
        } else {
            partyHolder = convertView.tag as PartyAutoCompleteHolder
        }

        return partyHolder.view
    }

    inner class PartyAutoCompleteHolder(binding: RowPartyItemViewBinding) {
        val view = binding.root
    }

    fun addItems(parties: List<AddPartyRequest>) {
        items?.clear()
        items?.addAll(parties)
        dataListAllItems.clear()
        dataListAllItems.addAll(parties)
        notifyDataSetChanged()
    }

    override fun getFilter(): Filter? {
        if (listFilter == null) {
            listFilter = ListFilter()
        }
        return listFilter
    }

    inner class ListFilter : Filter() {

        override fun performFiltering(constraint: CharSequence?): Filter.FilterResults? {
            var constraint = constraint
            val results = Filter.FilterResults()

            if (constraint != null && constraint.isNotEmpty()) {
                constraint = constraint.toString().toUpperCase()

                val filters = ArrayList<AddPartyRequest>()

                if (dataListAllItems.size === 0) {

                    val groupsResponse = AddPartyRequest("", "", "", "", "", "", "", "", "", "", "")

                    filters.add(groupsResponse)

                } else {

                    for (i in 0 until dataListAllItems.size) {
                        if (dataListAllItems.get(i).partyName.toUpperCase().contains(constraint)) {

                            val groupsResponse = AddPartyRequest(
                                dataListAllItems.get(i).address,
                                dataListAllItems.get(i).asOfToday,
                                dataListAllItems.get(i).currentBalance,
                                dataListAllItems.get(i).email,
                                dataListAllItems.get(i).gstIn,
                                dataListAllItems.get(i).partyName,
                                dataListAllItems.get(i).partyType,
                                dataListAllItems.get(i).phoneNumber,
                                dataListAllItems.get(i).state,
                                dataListAllItems.get(i).userCompanyId,
                                dataListAllItems.get(i).partyId
                            )

                            filters.add(groupsResponse)

                        }
                    }

                }
                results.count = filters.size
                results.values = filters
            } else {
                results.count = dataListAllItems.size
                results.values = dataListAllItems
            }

            return results
        }

        override fun publishResults(constraint: CharSequence, results: Filter.FilterResults?) {
            items = results?.values as ArrayList<AddPartyRequest>
            notifyDataSetChanged()
        }

    }

    override fun onItemClick(view: View, position: Int) {

    }
}

输入任何字符后我在自定义适配器中遇到的错误

java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter constraint
        at in.diittech.diitvyapar.ui.adapter.PartyAutoCompleteAdapter$ListFilter.publishResults(Unknown Source:24)
        at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:282)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

【问题讨论】:

    标签: android mvvm android-databinding autocompletetextview


    【解决方案1】:

    这就是我的做法。可能有点晚,但也许其他人可能会使用它。

    自动完成文本视图:

     class BindingAutoCompleteTextView(context: Context, attributeSet: AttributeSet) : AutoCompleteTextView(context, attributeSet) {
    
         var selectedItem: Any? = null
    
     }//Cls
    
     //=====================================================================================================//
     //=====================================================================================================//
    
     @InverseBindingAdapter(attribute = "app:selectedItem")
     fun getSelectedItem(bindingActv: BindingAutoCompleteTextView): Any? {
         return bindingActv.selectedItem
     }//getSelectedItem
    
     //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//
    
     @BindingAdapter("selectedItemAttrChanged")
     fun selectedItemAttrChanged(actv: BindingAutoCompleteTextView, listener: InverseBindingListener) {
         actv.setOnItemClickListener { parent, _, position, _ ->
             actv.selectedItem = parent.adapter.getItem(position)
             listener.onChange()
         }
     }//selectedItemAttrChanged
    
     //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//
    
     @BindingAdapter("app:adapter")
     fun setAdapter(actv: AutoCompleteTextView, adapter: FilterableBaseAdapter?) {
    
         adapter?.let {
             actv.setAdapter(adapter)
         }
    
     }//setAdapter
    
     //=====================================================================================================//
     //=====================================================================================================//
    
     /**
      * Class to be used as type parameter in functions
      */
     abstract class FilterableBaseAdapter : BaseAdapter(), Filterable
    
     //=====================================================================================================//
     //=====================================================================================================//
    

    布局:

    <?xml version="1.0" encoding="utf-8"?>
    
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:bind="http://schemas.android.com/tools">
    
    
        <data>
    
            <variable
                name="viewModel"
                type="ie.conecto.ui.salesOrder.SalesOrderViewModel" />
        </data>
    
    
        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
    
            <ie.conecto.infastructure.ui.BindingAutoCompleteTextView
                android:id="@+id/acCustomer"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="8dp"
                android:completionThreshold="2"
                android:hint="@string/select_customer"
                android:textAlignment="center"
                android:textSize="20sp"
                app:adapter="@{viewModel.adapter}"
                app:selectedItem="@={viewModel.orderItem}"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
    
            <TextView
                android:layout_width="match_parent"
                android:layout_height="19dp"
                android:background="@color/colorPrimaryLight"
                android:text='@{viewModel.orderItem.description}'
                android:textAlignment="center"
                app:layout_constraintTop_toBottomOf="@id/acCustomer" />
    
    
            <include
                layout="@layout/progress_overlay"
                bind:show="@{viewModel.showProgress}" />
    
        </androidx.constraintlayout.widget.ConstraintLayout>
    
    </layout>
    

    视图模型:

    private const val TAG = "SalesOrderViewModel"
    
    class SalesOrderViewModel(
        private val _productRepo: IProductRepo,
        private val _customerRepo: ICustomerRepo
    ) : ViewModel() {
    
    
        var orderItem = MutableLiveData<OrderItem?>()
    
    
        val products by lazyDeferred {
            _productRepo.getProducts()
        }
    
    
        val customers by lazyDeferred {
            _customerRepo.getCustomers()
        }
    
        val showProgress: LiveData<Boolean>
            get() = _showProgress
        private var _showProgress = MutableLiveData<Boolean>()
    
    
        val adapter: LiveData<ProductAutoCompleteTextViewAdapter>
            get() = _adapter
        private var _adapter = MutableLiveData<ProductAutoCompleteTextViewAdapter>()
    
        var backgroundTaskResultListener: BackgroundTaskResultListener? = null
    
    
        //--------------------------------------------------------------------------------/
    
        init {
            Coroutines.main {
                Log.d(TAG, "init")
                _showProgress.postValue(true)
    
                products
                    .await()
                    .observeForever { products ->
                        context.let {
                            _adapter.postValue(ProductAutoCompleteTextViewAdapter(products))
                            _adapter.value?.notifyDataSetChanged()
                            if (products.isNotEmpty())
                                _showProgress.postValue(false)
    
                        }
                    }//observe
    
            }//main
        }//init
    
        //--------------------------------------------------------------------------------//
    
    
    }//Cls
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      相关资源
      最近更新 更多