1. 方法一: findViewById
2. 方法二: viewBinding
使用方法二时,需要在app的build.gradle中android {…}属性中添加
viewBinding {enabled = true}
与使用findViewById相比,视图绑定优点:
1.null安全性:由于视图绑定会创建对视图的直接引用,因此不会因无效的视图ID而导致null指针异常的风险。 此外,当视图仅在布局的某些配置中存在时,在绑定类中包含其引用的字段将用@Nullable
2.类型安全性:每个绑定类中的字段具有与其在XML文件中引用的视图匹配的类型。 这意味着没有类强制转换异常的风险。
视图绑定缺点:
新建项目时不是默认的,需要修改build.gradle和java两个文件
举个栗子:
java文件:
public class FirstActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//调用布局文件中控件方法一
setContentView(R.layout.main);
TextView textView1 = (TextView) findViewById(R.id.textView1); // 获取对象
textView1.setText("第一次采用findViewById方法");
//调用布局文件中控件方法二
/**
* 在app的build.gradle中android {..}属性中添加
* viewBinding {enabled = true}
*/
/**
* 视图的命名规则:
* 如果为模块启用了绑定,则将为其包含的每个XML布局文件生成一个绑定类。 每个绑定类都包含对根视图和所有具有ID的视图的引用。 绑定类的名称是通过将XML文件的名称转换为大驼峰命名法并将单词“ Binding”添加到末尾来生成的。
*/
MainBinding mainBinding = MainBinding.inflate(getLayoutInflater()); //本行代码必须在setContentView(mainBinding.getRoot()); 命令前
setContentView(mainBinding.getRoot()); //会覆盖setContentView(R.layout.main);
mainBinding.textView2.setText("采用MainBinding");
//Q:可以直接使用下面的命令吗?不可以,java文件中没有定义textView2这个控件,会报错
//textView2.setText("采用MainBinding");
// //如果两种方案混合使用需重新调用findViewById,∵运行setContentView(mainBinding.getRoot());重新绑定布局文件中控件
textView1 = (TextView) findViewById(R.id.textView1); //由于运行setContentView后重新绑定布局文件中控件,此处需重新调用findViewById
// //Q:如果没有上一行代码,直接只用下面的命令会如何?没有定义textView1控件,下面代码无效。
textView1.setText("第二次采用findViewById方法");
}
}
main.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/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/var1" />
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/var2" />
</LinearLayout>
strings.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="var1">布局中定义的第一个TextView</string>
<string name="var2">布局中定义的第二个TextView</string>
</resources>
运行结果: