ViewBinding学习

使用kotlin-android-extensions发现被放弃了。要用ViewBinding,一些小问题记录一下。
先在model中的build.gradle中的android加上

    viewBinding {
        enabled = true
    }

或者是

    buildFeatures {
        viewBinding true
    }

但是这个要在buildiTypes前面,不然会有问题,而且这种方法不是官方提到的,是我搜到的,不知道有什么区别,现在懒得去理。
使用的时候最好要放在全局定义,然后在onCreate的时候初始化 ,Binding类的命名规则是将布局文件按驼峰方式重命名后,再加上Binding作为结尾

    private lateinit var binding: viewModelBinding

    override fun onCreate(savedInstanceState: Bundle) {
        super.onCreate(savedInstanceState)
        binding = viewModelBinding.inflate(layoutInflater)
        binding.name.setOnClickListener{
            //这里就可以正常使用了
        }
    }

但是在学习自定义控件,使用方法要变成

    private lateinit var binding: TitleBinding

    init {
        LayoutInflater.from(context).inflate(R.layout.title, this)
        val root = View.inflate(context, R.layout.title, this)
        binding = TitleBinding.bind(root)
        binding.titleBack.setOnClickListener {
            val activity=context as Activity
            activity.finish()
        }
        binding.titleEdit.setOnClickListener {
            Toast.makeText(context, "you clicked", Toast.LENGTH_SHORT).show()
        }
    }

暂时感觉到是因为自定义控件没有layoutInflater这东西,具体的后面遇上在深究
还有在ListView中如果使用viewbinding来绑定adapter是无法实现的。

class MainActivity : AppCompatActivity() {
private val data = listOf("Apple", "Banana", "Orange", "Watermelon",
    "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango")
private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    val listviewdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data)
    binding.listview1.adapter = listviewdapter
    
    }
}

这种情况ListView不会显示出列表信息,因为列表项在创建列表时不会膨胀。绑定根本不适用于列表视图。如果要在列表视图中使用视图绑定,则绑定必须在适配器中。

在recycleView.Adapter中使用

class PlaceAdapter(private val fragment: Fragment,private val placeList: List<Place>):
        RecyclerView.Adapter<PlaceAdapter.ViewHolder>(){

    inner class ViewHolder(Binding:PlaceItemBinding):RecyclerView.ViewHolder(Binding.root){
        val placeName:TextView=Binding.placeName
        val placeAddress:TextView=Binding.placeAddress
    }

    override fun getItemCount(): Int {
        return placeList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val place = placeList[position]
        holder.placeName.text = place.name
        holder.placeAddress.text = place.address
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val placeItemBinding = PlaceItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)

        return ViewHolder(placeItemBinding)
    }
}
posted @ 2022-04-11 20:19  一无所知小白龙  阅读(281)  评论(0编辑  收藏  举报