什么是View Binding
View Binding是Android Studio 3.6推出的新特性,目的是為了替代findViewById(內(nèi)部實(shí)現(xiàn)還是使用findViewById)。。在啟動(dòng)視圖綁定后,系統(tǒng)會(huì)為改模塊中的每個(gè)xml文件生成一個(gè)綁定類,綁定類的實(shí)例包含對(duì)在相應(yīng)布局中具有 ID 的所有視圖的直接引用。
View Binding 的優(yōu)點(diǎn)
-
Null 安全:由于視圖綁定會(huì)創(chuàng)建對(duì)視圖的直接引用,因此不存在因視圖 ID 無(wú)效而引發(fā) Null 指針異常的風(fēng)險(xiǎn)。此外,如果視圖僅出現(xiàn)在布局的某些配置中,則綁定類中包含其引用的字段會(huì)使用
@Nullable標(biāo)記。 - 類型安全:每個(gè)綁定類中的字段均具有與它們?cè)?XML 文件中引用的視圖相匹配的類型。這意味著不存在發(fā)生類轉(zhuǎn)換異常的風(fēng)險(xiǎn)。
如何啟用View Binding 功能
android {
...
viewBinding {
enabled = true
}
}
}
如果想在生成綁定類時(shí)忽略某個(gè)布局文件,將 tools:viewBindingIgnore="true" 屬性添加到相應(yīng)布局文件的根視圖中:
<?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"
tools:context=".MainActivity">
<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>
怎么去使用View Binding
為用視圖綁定功能后,系統(tǒng)會(huì)為該模塊中包含的每個(gè) XML 布局文件生成一個(gè)綁定類。這個(gè)類的類名是以xml布局文件名去掉下?lián)Q線后,單詞首字母大寫加上Binding命名的。如activity_main.xml生成的類ActivityMainBinding.
-
如何在Activity中設(shè)置綁定,請(qǐng)?jiān)?Activity 的 onCreate() 方法中執(zhí)行以下步驟:
調(diào)用生成的綁定類中包含的靜態(tài)
inflate()方法。此操作會(huì)創(chuàng)建該綁定類的實(shí)例以供 Activity 使用。通過(guò)調(diào)用
getRoot()方法或使用 Kotlin 屬性語(yǔ)法獲取對(duì)根視圖的引用。將根視圖傳遞到 setContentView(),使其成為屏幕上的活動(dòng)視圖。
//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); //關(guān)鍵代碼 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","點(diǎn)擊了按鈕"); } }); } } -
如何在 Fragment 中使用視圖綁定 請(qǐng)?jiān)?Fragment 的 onCreateView()方法中執(zhí)行以下步驟(注意:Fragment 的存在時(shí)間比其視圖長(zhǎng)。請(qǐng)務(wù)必在 Fragment 的 onDestroyView() 方法中清除對(duì)綁定類實(shí)例的所有引用。)
調(diào)用生成的綁定類中包含的靜態(tài)
inflate()方法。此操作會(huì)創(chuàng)建該綁定類的實(shí)例以供 Fragment 使用。通過(guò)調(diào)用
getRoot()方法或使用 Kotlin 屬性語(yǔ)法獲取對(duì)根視圖的引用。-
從
onCreateView()方法返回根視圖,使其成為屏幕上的活動(dòng)視圖。如果view已經(jīng)創(chuàng)建可以在onViewCreated()中使用bind(view)方法。官方示例
//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; public MyFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @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", "點(diǎn)擊了按鈕"); } }); } @Override public void onDestroy() { super.onDestroy(); binding = null; }//在onViewCreated中使用View Binding public class MyFragment extends Fragment { private FragmentMyBinding binding; public MyFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_my,container,false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); FragmentMyBinding binding = FragmentMyBinding.bind(view); this.binding = binding; binding.textView.setText("這是Fragment"); binding.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d("Fragment", "點(diǎn)擊了按鈕"); } }); } @Override public void onDestroy() { super.onDestroy(); binding = null; }使用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","點(diǎn)擊按鈕"); } }); } }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","點(diǎn)擊按鈕"); } }); } }
轉(zhuǎn)載自:
作者:lq_ios
鏈接:http://www.itdecent.cn/p/66728b95baaa