在 在Android中使用注解绑定控件和事件 中, 给大家介绍了使用第三方库: Butterknife 来替代 findViewById 进行控件绑定的方式。在 Android Studio 3.6 以后,官方提供了更好的解决方案,这就是: viewBinding。 本文简单介绍 viewBinding 的用法。
在本文中,我们继续使用在 在Android中使用注解绑定控件和事件 中使用的登录页面的案例。 在 activty_main.xml 文件中构造一个简单的登录页面,包括一个名为 txtUserId 的文本框,一个名为 txtPwd 的密码框, 一个名为 btnLogin 的按钮。
开启试图绑定
因为是官方的解决方案,所以开启试图绑定功能,不需要引入其它额外的依赖,只需要在模块的 build.gradle 文件中添加 viewBinding 选项即可:
1 2 3
| viewBinding { enabled = true }
|
完整的 build.gradle (Module:app) 文件内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| apply plugin: 'com.android.application'
android { compileSdkVersion 29 buildToolsVersion "29.0.3"
defaultConfig { applicationId "cn.com.hohistar.study.android" minSdkVersion 16 targetSdkVersion 29 versionCode 1 versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" }
viewBinding { enabled = true }
compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }
buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } }
}
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' }
|
在 Activity 类中使用绑定
当我们开启试图绑定或, Android Studio 会为项目中的每个布局文件生成对应的绑定类,如 activity_main.xml 会生成对应名为: ActivityMainBinding 的类。里面包含了在 xml 中对应控件的类的定义。 这样我们就可以在程序中直接使用该控件, 修改后的 MainActivity.java 代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| private static final String TAG = "[" + MainActivity.class.getSimpleName() +"]";
ActivityMainBinding binding = null;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
binding.btnLogin.setOnClickListener( v -> { Log.d(TAG, "Login clicked. userId = " + binding.txtUserId.getText().toString()); });
setContentView(binding.getRoot()); }
|
可以看到,在 activity_main.xml 中定义的控件,生成了 ActivityMainBinding 中的类,我们可以用属性的方式直接引用,非常方便。