概述
dataBinding
雙向綁定,viewBinding
單向綁定.
它用來替代findViewById()
,可以看作輕量級的dataBinding
.
Kotlin中雖有synthetic特性,方便獲取控件引用.但這個特性作用的範圍是全局的, 很容易不小心引入其他佈局中的控件引用造成空指針.
注意事項
Android Studio 3.6及以上才支持viewBinding
.
在Studio版本爲3.6及以上時,還需要保證classpath
在com.android.tools.build:gradle:3.6.0
以上,否則會報錯.
Could not find method viewBinding() for arguments [build_avr407103co4pp1wtvc9g3xyy$_run_closure1$_closure5@1ad89b9c] on object of type com.android.build.gradle.internal.dsl.BaseAppModuleExtension.
classpath
在com.android.tools.build:gradle:3.6.0
以上時,還要保證gradle版本在gradle-5.6.4-all
以上.
使用
配置
android {
// 相應的Module APP下的gradle中配置
viewBinding {
enabled = true
}
}
Activity中用法
XML佈局文件,xml的文件名稱爲:activity_main_1.xml
<?xml version="1.0" encoding="utf-8"?>
< RelativeLayout xmlns: android= " http://schemas.android.com/apk/res/android"
xmlns: app= " http://schemas.android.com/apk/res-auto"
xmlns: tools= " http://schemas.android.com/tools"
android: layout_width= " match_parent"
android: layout_height= " match_parent"
tools: context= " .MainActivity" >
< TextView
android: id= " @+id/tv1"
android: layout_width= " match_parent"
android: layout_height= " 40dp" />
< TextView
android: id= " @+id/tv2"
android: layout_width= " match_parent"
android: layout_height= " 40dp" />
</ RelativeLayout>
MainActivity中用法
public class MainActivity extends AppCompatActivity {
private ActivityMain1Binding binding;
@Override
protected void onCreate ( Bundle savedInstanceState) {
super . onCreate ( savedInstanceState) ;
binding = ActivityMain1Binding. inflate ( getLayoutInflater ( ) ) ;
setContentView ( binding. getRoot ( ) ) ;
binding. tv1. setText ( "1" ) ;
binding. tv2. setText ( "2" ) ;
}
}
Fragment中用法
XML佈局,xml的文件名稱爲:first_fragment_1.xml
<?xml version="1.0" encoding="utf-8"?>
< LinearLayout xmlns: android= " http://schemas.android.com/apk/res/android"
android: layout_width= " match_parent"
android: layout_height= " match_parent"
android: orientation= " vertical" >
< TextView
android: id= " @+id/tv1"
android: layout_width= " match_parent"
android: layout_height= " 40dp" />
< TextView
android: id= " @+id/tv2"
android: layout_width= " match_parent"
android: layout_height= " 40dp" />
</ LinearLayout>
FirstFragment中用法
public class FirstFragment extends Fragment {
private static final String TAG = FirstFragment. class . getName ( ) ;
private FirstFragment1Binding binding;
@Nullable
@Override
public View onCreateView ( @NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding= FirstFragment1Binding. inflate ( getLayoutInflater ( ) ) ;
binding. tv1. setText ( "1" ) ;
binding. tv2. setText ( "1" ) ;
return binding. getRoot ( ) ;
}
}
參考資料一
參考資料二
參考資料三