ViewBinding
生活随笔
收集整理的這篇文章主要介紹了
ViewBinding
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
ViewBinding
- 1.開啟
- 2.Activity中的使用
- 3.Fragment中的使用
- 4.布局可復(fù)用
- 5.可以和butterknife混用
- 6.自定義View中可以使用
- 7.點(diǎn)擊事件
- 參考地址
1.開啟
AS 3.6:
android {...viewBinding.enabled = true }AS 4.0:
android {...buildFeatures{viewBinding true} }注意:如果AS版本是高版本,而gradle版本是低版本,那么會(huì)出現(xiàn) buildFeatures 找不到的情況.
比如在AS4.2上使用gradle3.6.4,就會(huì)出現(xiàn)我描述的問題;這樣的話你需要升級(jí)gradle,我測(cè)試的話,AS4.2上gradle是使用4.0.0就可以正常使用了。
2.Activity中的使用
private ActivityMainBinding binding;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);binding = ActivityMainBinding.inflate(getLayoutInflater());setContentView(binding.getRoot());}...//使用的時(shí)候:binding.bottomBar.addItem(homeTab).addItem(tripTab).addItem(serviceTab).addItem(selfTab);AS4.0之前的版本
出現(xiàn)異常:安卓ViewBinding出現(xiàn)ActivityMainBinding類不存在
需要在布局內(nèi)添加context
3.Fragment中的使用
在fragment中有兩種注入方式,一種是跟上面一樣
private FragmentMyBinding binding;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {binding = FragmentMyBinding.inflate(inflater, container, false);return binding.getRoot();}另一種:
onCreateView中正常綁定,onViewCreated中再綁定View
@Nullable@Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {View view = inflater.inflate(bindLayout(), container, false);return view;}@Overridepublic void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {super.onViewCreated(view, savedInstanceState);binding = FragmentMessageBinding.bind(view);}4.布局可復(fù)用
我在使用webview的時(shí)候復(fù)用了布局,沒有問題。AS4.2&gradle4.0
5.可以和butterknife混用
方便過度到viewbinding
6.自定義View中可以使用
// LayoutInflater inflater = LayoutInflater.from(getContext()); // View view; // view = inflater.inflate(R.layout.view_me_history_score, this); // ButterKnife.bind(this, view); //或binding = ViewMeHistoryScoreBinding.inflate(LayoutInflater.from(getContext()));addView(binding.getRoot());7.點(diǎn)擊事件
可以配合rxbinding使用
參考地址
Android View Binding的使用:https://www.jianshu.com/p/66728b95baaa
總結(jié)
以上是生活随笔為你收集整理的ViewBinding的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: EndNote添加其他参考文献格式教程
- 下一篇: 【bzoj 3864】Hero meet