简体   繁体   中英

Android Kotlin AutoCompleteTextView item shows whole item Object when clicked

So I have an AutoCompleteTextView that its dropdownlist populated with data from an array of object that formed from two different arrays by using the zip function.

What I want is that when each item of the AutoCompleteTextView dropdown item is clicked, it'll return one of the attribute of the clicked item object.

(This question is kind of similar with this question, however I still do not understand what to do even after reading the comments).

This is the snippet code from the Fragment where AutoCompleteTextView newProcodeEditFormEditText is declared:

 val procodeRecommendationList = allProductCodeList.zip(allProductNameList)
            .map { (allProductCodeList, allProductNameList) -> ProcodeRecommendationListDataClass(allProductCodeList, allProductNameList) }

        //This is where the created list of object being logged
        Log.i("Order", "Created List of objects: $procodeRecommendationList")


        //Set up adapter for these recommender
        val recommendedProductNameListAdapter = ArrayAdapter((activity as AppCompatActivity), android.R.layout.simple_list_item_1, allProductNameList)
        val recommendedProductCodeListAdapter = ProcodeRecommendationAdapter(activity as AppCompatActivity, R.layout.procode_recommendation_list_item_layout, procodeRecommendationList.toTypedArray())

        newProcodeEditFormEditText.threshold = 1
        newProductNameEditFormEditText.threshold = 1


        //Connect the adapter to each editText
        newProcodeEditFormEditText.setAdapter(recommendedProductCodeListAdapter)
        newProductNameEditFormEditText.setAdapter(recommendedProductNameListAdapter)


        //This is the onclick listener for the items in the AutoCompleteTextView Dropdown
        newProcodeEditFormEditText.setOnItemClickListener { parent, view, position, id ->
            val selectedItem = parent.getItemAtPosition(position)
            Toast.makeText((activity as AppCompatActivity), "Selected : ".plus(selectedItem), Toast.LENGTH_LONG).show()

            Log.i("Order", "Selected item: ${selectedItem}")

        }

This is the created List of object procodeRecommendationList as shown in the LogCat:

在此处输入图像描述

And this is what the clicked item returned as shown in the LogCat (Stored in the variable selectedItem ):

在此处输入图像描述

As expected, it shown in the AutoCompleteTextView like this: 在此处输入图像描述

And this is the Custom adapter i use for showing the items in the AutoCompleteTextView Dropdown:

  class ProcodeRecommendationAdapter(private val c: Context,
                                   @LayoutRes private val layoutResource: Int,
                                   private val items: Array<ProcodeRecommendationListDataClass>)
    : ArrayAdapter<ProcodeRecommendationListDataClass>(c, layoutResource, items) {

    var filteredRecommendations: List<ProcodeRecommendationListDataClass> = listOf()

    override fun getCount(): Int = filteredRecommendations.size

    override fun getItem(position: Int): ProcodeRecommendationListDataClass = filteredRecommendations[position]

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view = convertView ?: LayoutInflater.from(c).inflate(layoutResource, parent, false)

        view.tvProcode.text = filteredRecommendations[position].procode
        view.tvProname.text = filteredRecommendations[position].productName

        return view
    }

    override fun getFilter(): Filter {
        return object : Filter() {
            override fun publishResults(charSequence: CharSequence?, filterResults: FilterResults) {
                @Suppress("UNCHECKED_CAST")
                filteredRecommendations = filterResults.values as List<ProcodeRecommendationListDataClass>
                notifyDataSetChanged()
            }

            override fun performFiltering(charSequence: CharSequence?): FilterResults {
                val queryString = charSequence?.toString()?.toLowerCase()

                val filterResults = FilterResults()
                filterResults.values = if (queryString == null || queryString.isEmpty())
                    items.asList()
                else
                    items.filter {
                        it.procode?.toLowerCase(Locale.ROOT)!!.contains(queryString)
                    }

                return filterResults
            }
        }
    }

}

And this is the data class I use:

 data class ProcodeRecommendationListDataClass(
    val procode: String?,
    val productName: String?
)

So far it has no problem in populating the AutoCompleteTextView dropdown items.

在此处输入图像描述

What I want is that I want to get the procode attribute so it'll only show 0100009 in the AutoCompleteTextView instead of ProcodeRecommendationListDataClass(procode=0100009, productName=TARIVID OTIC 3MG EAR DROPS 5ML) when the item is clicked.

How can I achieve something like that? Where should I change in the adapter code? If There's any detail I miss, just let me know!

Edit:

If anyone needs the AutoCompleteTextview item layout, here:

    <androidx.constraintlayout.widget.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="wrap_content"
    android:padding="16dp">

    <TextView
        android:id="@+id/tvProcode"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tvProname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:textStyle="bold|italic"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tvProcode" />

</androidx.constraintlayout.widget.ConstraintLayout>

When you select any item from AutoCompleteTextView it will be returning object of ProcodeRecommendationListDataClass

You need to access it like below code

newProcodeEditFormEditText.setOnItemClickListener { parent, view, position, id ->
            val selectedItem = parent.getItemAtPosition(position) as ProcodeRecommendationListDataClass
            Toast.makeText((activity as AppCompatActivity), "Selected : ".plus(selectedItem.procode), Toast.LENGTH_LONG).show()
            Toast.makeText((activity as AppCompatActivity), "Selected : ".plus(selectedItem.productName), Toast.LENGTH_LONG).show()

            newProcodeEditFormEditText.setText(selectedItem.procode)
            Log.i("Order", "Selected item: ${selectedItem}")

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM