安卓kotlin使用databinding功能

Step 1: Enable data binding

Open the build.gradle (Module: app) file.

Inside the android section, before the closing brace, add a buildFeatures section and set dataBinding to true.

buildFeatures {
    dataBinding true
}

Because of kotlin , you should use the kotlin-kapt plugin to avoid the warning in AS.

//also in build.gradle (Module: app) file
plugins {
    id 'kotlin-kapt'
}

Step 2: Change layout file to be usable with data binding

To work with data binding, you need to wrap your XML layout with a <layout> tag.

Open the activity_main.xml file.

Add <layout></layout> as the outermost tag around the <LinearLayout>.

<layout>
   <LinearLayout ... >
   ...
   </LinearLayout>
</layout>

tips: use the Alt+Enter in the LinearLayout tag to quickly generate the <layout >wrap

How to Use data-binding in Activity/Fragment

  • first method
private lateinit var binding: ActivityMainBinding
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

in fragment with the databinding:

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                         savedInstanceState: Bundle?): View? {
   val binding = DataBindingUtil.inflate<FragmentTitleBinding>(inflater,
           R.layout.fragment_title,container,false)
   return binding.root
   }
  • Second method(easier)
val binding = FragmentTitleBinding.inflate(inflater)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值