findViewById() 方法是Android的View 和Activity 类中的一个方法。
该方法用于在你的XML布局中通过其android:id 属性找到一个现有的视图。
例如,假设你的XML布局中有一个TextView ,定义如下。
<TextView
android:id="@+id/id_text_view"
android:text="Hello World!"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
你可以用下面的代码在你的Activity 类中获得上面的TextView 。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView myTextView = findViewById(R.id.id_text_view);
}
对于任何有效的安卓View 对象,例如Button 或CheckBox 视图,也可以这样做。
当你调用findViewById() 方法时,该方法通常是从AppCompatActivity 类中调用的,该类是Activity 类的一个子类。
findViewById() 方法只接受一个参数,它是视图的id ,有int 类型的引用。
@Override
public <T extends View> T findViewById(@IdRes int id) {
return getDelegate().findViewById(id);
}
Android框架会生成一个你在XML布局中指定的ID的内部引用。该内部引用是一个int 类型。
你需要在你的代码中通过调用R.id ,来引用这个生成的int 值。
在Kotlin中使用findById
在Kotlin中,你可以使用findViewById() 方法的语法如下。
val myTextView = findViewById<TextView>(R.id.id_text_view)
你需要在角括号内指定视图的通用类型<> ,如上所示。
这就是你在开发Android项目时如何使用findViewById() 方法。👍