How to add chips from Material Components library to input field in android?

后端 未结 4 681
长情又很酷
长情又很酷 2020-12-07 23:43

I\'ve seen that in android-P google add new material components library which contains material chips:

Material components for android

Material.io chips us

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 23:52

    We can do this by using material chips design itself without adding any extra styles.

    Add it on app gradle For AndroidX

    implementation 'com.google.android.material:material:1.0.0-beta01'

    For earlier than AndroidX use this

    implementation 'com.android.support:design:28.0.0'

    Fragment

    class EntryChipDemoFragment : Fragment() {
        private lateinit var mView: View
    
        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                                  savedInstanceState: Bundle?): View? {
            mView = inflater.inflate(R.layout.fragment_entry_chip_demo, container, false)
    
            mView.etValue.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, _ ->
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    val txtVal = v.text
                    if(!txtVal.isNullOrEmpty()) {
                        addChipToGroup(txtVal.toString(), mView.chipGroup2)
                        mView.etValue.setText("")
                    }
    
                    return@OnEditorActionListener true
                }
                false
            })
    
            return mView
        }
    
    
        private fun addChipToGroup(txt: String, chipGroup: ChipGroup) {
            val chip = Chip(context)
            chip.text = txt
    //        chip.chipIcon = ContextCompat.getDrawable(requireContext(), baseline_person_black_18)
            chip.isCloseIconEnabled = true
            chip.setChipIconTintResource(R.color.chipIconTint)
    
            // necessary to get single selection working
            chip.isClickable = false
            chip.isCheckable = false
            chipGroup.addView(chip as View)
            chip.setOnCloseIconClickListener { chipGroup.removeView(chip as View) }
            printChipsValue(chipGroup)
        }
    
        private fun printChipsValue(chipGroup: ChipGroup) {
            for (i in 0 until chipGroup.childCount) {
                val chipObj = chipGroup.getChildAt(i) as Chip
                Log.d("Chips text :: " , chipObj.text.toString())
    
            }
        }
    
        companion object {
            @JvmStatic
            fun newInstance() = EntryChipDemoFragment()
        }
    }
    

    XML File:

    
    
        
    
            
    
            
    
            
    
            
    
                
    
            
    
        
    
    
    
    

    For more reference Click Here

提交回复
热议问题