什么是View Binding
View Binding是Android Studio 3.6推出的新特性摔寨,目的是為了替代findViewById(內(nèi)部實現(xiàn)還是使用findViewById)犀变。。在啟動視圖綁定后,系統(tǒng)會為改模塊中的每個xml文件生成一個綁定類,綁定類的實例包含對在相應布局中具有 ID 的所有視圖的直接引用砰左。
View Binding 的優(yōu)點
-
Null安全:由于視圖綁定會創(chuàng)建對視圖的直接引用箭券,因此不存在因視圖 ID 無效而引發(fā) Null 指針異常的風險允华。此外井联,如果視圖僅出現(xiàn)在布局的某些配置中卜壕,則綁定類中包含其引用的字段會使用
@Nullable
標記。 - 類型安全:每個綁定類中的字段均具有與它們在 XML 文件中引用的視圖相匹配的類型低矮。這意味著不存在發(fā)生類轉(zhuǎn)換異常的風險。
如何啟用View Binding 功能
android {
...
viewBinding {
enabled = true
}
}
}
如果想在生成綁定類時忽略某個布局文件被冒,將 tools:viewBindingIgnore="true"
屬性添加到相應布局文件的根視圖中:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:viewBindingIgnore="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
生成的 ActivityTestBinding.java :
文件位置在 (app/build/generated/data_binding_base_class_source_out/debug/out/<包路徑>/databinding/ActivityTestBinding.java)
public final class ActivityTestBinding implements ViewBinding {
@NonNull
private final ConstraintLayout rootView;
private ActivityTestBinding(@NonNull ConstraintLayout rootView) {
this.rootView = rootView;
}
@Override
@NonNull
public ConstraintLayout getRoot() {
return rootView;
}
@NonNull
public static ActivityTestBinding inflate(@NonNull LayoutInflater inflater) {
return inflate(inflater, null, false);
}
@NonNull
public static ActivityTestBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup parent, boolean attachToParent) {
View root = inflater.inflate(R.layout.activity_test, parent, false);
if (attachToParent) {
parent.addView(root);
}
return bind(root);
}
@NonNull
public static ActivityTestBinding bind(@NonNull View rootView) {
if (rootView == null) {
throw new NullPointerException("rootView");
}
return new ActivityTestBinding((ConstraintLayout) rootView);
}
}
怎么去使用View Binding
為用視圖綁定功能后军掂,系統(tǒng)會為該模塊中包含的每個 XML 布局文件生成一個綁定類。這個類的類名是以xml布局文件名去掉下?lián)Q線后昨悼,單詞首字母大寫加上Binding命名的蝗锥。如activity_main.xml生成的類ActivityMainBinding.
-
如何在
Activity
中設置綁定,請在Activity
的onCreate()
方法中執(zhí)行以下步驟:調(diào)用生成的綁定類中包含的靜態(tài)
inflate()
方法率触。此操作會創(chuàng)建該綁定類的實例以供 Activity 使用终议。通過調(diào)用
getRoot()
方法或使用 Kotlin 屬性語法獲取對根視圖的引用。將根視圖傳遞到
setContentView()
葱蝗,使其成為屏幕上的活動視圖穴张。
//activity_main.xml <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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"> <Button android:id="@+id/button" android:layout_width="100dp" android:layout_height="40dp" android:text="這是按鈕" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> <TextView android:id="@+id/textView" android:layout_width="100dp" android:layout_height="40dp" android:gravity="center" android:text="Hello World!" app:layout_constraintBottom_toTopOf="@+id/button" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
//MainActivity.java public class MainActivity extends AppCompatActivity { private ActivityMainBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //關鍵代碼 binding = ActivityMainBinding.inflate(getLayoutInflater()); View rootView = binding.getRoot(); setContentView(rootView); //如何使用 binding.textView.setText("這是修改的"); binding.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d("Main","點擊了按鈕"); } }); } }
-
如何在
Fragment
中使用視圖綁定,請在Fragment
的onCreateView()
方法中執(zhí)行以下步驟(注意:Fragment 的存在時間比其視圖長两曼。請務必在Fragment
的onDestroyView()
方法中清除對綁定類實例的所有引用皂甘。)調(diào)用生成的綁定類中包含的靜態(tài)
inflate()
方法。此操作會創(chuàng)建該綁定類的實例以供 Fragment 使用悼凑。通過調(diào)用
getRoot()
方法或使用 Kotlin 屬性語法獲取對根視圖的引用偿枕。從
onCreateView()
方法返回根視圖,使其成為屏幕上的活動視圖户辫。
//fragment_my.xml <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="40dp" android:text="這是Fragment按鈕" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="40dp" android:gravity="center" android:text="這是FragmentTextView" app:layout_constraintBottom_toTopOf="@+id/button" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
public class MyFragment extends Fragment { private FragmentMyBinding binding; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentMyBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); binding.textView.setText("這是Fragment"); binding.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d("Fragment", "點擊了按鈕"); } }); } @Override public void onDestroy() { super.onDestroy(); binding = null; }
-
如何在
Adapter
中使用視圖綁定渐夸,首先改造ViewHolder,讓其構造函數(shù)接收FruitItemBinding這個參數(shù)渔欢。但是注意墓塌,ViewHolder的父類RecyclerView.ViewHolder它只會接收View類型的參數(shù),因此我們需要調(diào)用binding.root獲得fruit_item.xml中根元素的實例傳給RecyclerView.ViewHolder。class FruitAdapter(val fruitList: List<Fruit>) : RecyclerView.Adapter<FruitAdapter.ViewHolder>() { inner class ViewHolder(binding: FruitItemBinding) : RecyclerView.ViewHolder(binding.root) { val fruitImage: ImageView = binding.fruitImage val fruitName: TextView = binding.fruitName } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = FruitItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val fruit = fruitList[position] holder.fruitImage.setImageResource(fruit.imageId) holder.fruitName.text = fruit.name } override fun getItemCount() = fruitList.size
-
如何在
自定義組合控件
中使用視圖綁定桃纯,直接inflate即可class MainTabView : FrameLayout { private var viewBinding = ItemTabMainBinding.inflate(LayoutInflater.from(context), this, true) private lateinit var tabEntity: TabEntity constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) fun getTabProperty() = tabEntity fun setup(tabEntity: TabEntity) { this.tabEntity = tabEntity setupInternal() } fun select(select: Boolean) { selectInternal(select) } private fun setupInternal() { Glide.with(viewBinding.ivTabNormal).load(tabEntity.normalIconRes).into(viewBinding.ivTabNormal) Glide.with(viewBinding.ivTabSelected).load(tabEntity.selectedIconRes).into(viewBinding.ivTabSelected) } private fun selectInternal(select: Boolean) { viewBinding.ivTabNormal.isVisible = !select viewBinding.ivTabSelected.isVisible = select viewBinding.vDot.isVisible = select } data class TabEntity(val tab: MainTab, val normalIconRes: Int, val selectedIconRes: Int) }
使用View Binding 寫的基類
public class BaseActivity<T extends ViewBinding> extends AppCompatActivity {
protected T viewBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
Class cls = (Class) type.getActualTypeArguments()[0];
try {
Method inflate = cls.getDeclaredMethod("inflate", LayoutInflater.class);
viewBinding = (T) inflate.invoke(null, getLayoutInflater());
setContentView(viewBinding.getRoot());
} catch (NoSuchMethodException | IllegalAccessException| InvocationTargetException e) {
e.printStackTrace();
}
}
}
//使用
public class MainActivity extends BaseActivity<ActivityMainBinding> {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewBinding.button.setText("這是 MainActivity ViewBinding");
viewBinding.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("MainView","點擊按鈕");
}
});
}
}
public class BaseFragment<T extends ViewBinding> extends Fragment {
protected T viewBinding;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
Class cls = (Class) type.getActualTypeArguments()[0];
try {
Method inflate = cls.getDeclaredMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class);
viewBinding = (T) inflate.invoke(null, inflater, container, false);
} catch (NoSuchMethodException | IllegalAccessException| InvocationTargetException e) {
e.printStackTrace();
}
return viewBinding.getRoot();
}
}
//使用
public class MainFragment extends BaseFragment<FragmentMainBinding>{
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
viewBinding.button.setText("這是 MainFragment ViewBinding");
viewBinding.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("MainView","點擊按鈕");
}
});
}
}