Android ViewBinding的使用詳解
最近Android Studio 升級後 butterknife 有一個警告:
Resource IDs will be non-final in Android Gradle Plugin version 5.0, avoid using them as annotation attributes
查看官網發現:
butterknife已經棄用,建議使用 view binding 替換。
一、什麼是view binding
官方介紹:
通過視圖綁定功能,您可以更輕松地編寫可與視圖交互的代碼。在模塊中啟用視圖綁定之後,系統會為該模塊中的每個 XML 佈局文件生成一個綁定類。綁定類的實例包含對在相應佈局中具有 ID 的所有視圖的直接引用。
在大多數情況下,視圖綁定會替代 findViewById。
設置說明
- android studio 必須是3.6及更高版本。
- com.android.tools.build:gradle 需要 3.6.0及更高版本。
- build.gradle 中啟用功能,不同模塊要分別設置。
android { ... viewBinding { enabled = true } buildFeatures { viewBinding = true } }
二、基本用法
Activity中使用
在 Activity 的 onCreate() 方法中執行以下步驟:
- 調用生成的綁定類中包含的靜態 inflate() 方法。
- 通過調用 getRoot() 方法獲取對根視圖的引用。
- 將根視圖傳遞到 setContentView(),使其成為屏幕上的活動視圖。
private ResultProfileBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ResultProfileBinding.inflate(getLayoutInflater()); View view = binding.getRoot(); setContentView(view); }
現在即可使用該綁定類的實例來引用任何視圖:
binding.getName().setText(viewModel.getName()); binding.button.setOnClickListener(new View.OnClickListener() { viewModel.userClicked() });
現在即可使用該綁定類的實例來引用任何視圖:
binding.getName().setText(viewModel.getName()); binding.button.setOnClickListener(new View.OnClickListener() { viewModel.userClicked() });
Fragment 中使用
在 Fragment 的 onCreateView() 方法中執行以下步驟:
- 調用生成的綁定類中包含的靜態 inflate() 方法。
- 通過調用 getRoot() 方法獲取對根視圖的引用。
- 從 onCreateView() 方法返回根視圖,使其成為屏幕上的活動視圖。
- 在 onDestroyView() 中銷毀綁定類。
private ResultProfileBinding binding; @Override public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = ResultProfileBinding.inflate(inflater, container, false); View view = binding.getRoot(); return view; } @Override public void onDestroyView() { super.onDestroyView(); binding = null; }
Adapter 中使用
public class TestAdapter extends BaseAdapter { private List<String> datas; private final LayoutInflater mInflater; public TestAdapter(List<String> datas, Context context) { this.datas = datas; this.mInflater = LayoutInflater.from(context); } @Override public int getCount() { return datas.size(); } @Override public Object getItem(int i) { return i; } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder viewHolder; if (view == null) { AdapterTestBinding binding = AdapterTestBinding.inflate(mInflater, viewGroup, false); viewHolder = new ViewHolder(binding); view = binding.getRoot(); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } viewHolder.binding.tvContent.setText(datas.get(i)); return view; } static class ViewHolder { private final AdapterTestBinding binding; public ViewHolder(AdapterTestBinding binding) { this.binding = binding; } } }
三、瞭解源碼實現
項目運行後,每個佈局文件都會生成對應的binding類,比如 activity_main.xml 會生成 ActivityMainBinding.java 文件,路徑如下:
app\build\generated\data_binding_base_class_source_out\debug\out\包名\databinding
代碼其實很簡單就是加載佈局,然後對控件進行初始化:
public final class ActivityMainBinding implements ViewBinding { @NonNull private final LinearLayout rootView; @NonNull public final WebView wv; private ActivityMainBinding(@NonNull LinearLayout rootView, @NonNull WebView wv) { this.rootView = rootView; this.wv = wv; } @Override @NonNull public LinearLayout getRoot() { return rootView; } @NonNull public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater) { return inflate(inflater, null, false); } @NonNull public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup parent, boolean attachToParent) { View root = inflater.inflate(R.layout.activity_main, parent, false); if (attachToParent) { parent.addView(root); } return bind(root); } @NonNull public static ActivityMainBinding bind(@NonNull View rootView) { // The body of this method is generated in a way you would not otherwise write. // This is done to optimize the compiled bytecode for size and performance. String missingId; missingId: { WebView wv = rootView.findViewById(R.id.wv); if (wv == null) { missingId = "wv"; break missingId; } return new ActivityMainBinding((LinearLayout) rootView, wv); } throw new NullPointerException("Missing required view with ID: ".concat(missingId)); } }
ViewBinding 的源碼如下:
public interface ViewBinding { /** * Returns the outermost {@link View} in the associated layout file. If this binding is for a * {@code <merge>} layout, this will return the first view inside of the merge tag. */ @NonNull View getRoot(); }
可以對代碼稍加改造,減少 Activity 、Fragment 、Adapter 中的重復代碼。
BaseActivity
public abstract class BaseActivity<T extends ViewBinding> extends AppCompatActivity { protected T binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = getBinding(); setContentView(binding.getRoot()); } protected abstract T getBinding(); }
BaseFragment
public abstract class BaseFragment<T extends ViewBinding> extends Fragment { protected Context context; protected T binding; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { binding = getBinding(inflater, container); return binding.getRoot(); } protected abstract T getBinding(LayoutInflater inflater, ViewGroup container); @Override public void onDestroyView() { super.onDestroyView(); binding = null; } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); this.context = context; } @Override public void onDetach() { super.onDetach(); this.context = null; } }
public class TestFragment extends BaseFragment<FragmentTestBinding>{ @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); binding.tvContent.setText("this is test"); } @Override protected FragmentTestBinding getBinding(LayoutInflater inflater, ViewGroup container) { return FragmentTestBinding.inflate(inflater, container, false); } }
BaseAdapter
public abstract class MyAdapter<T extends ViewBinding> extends BaseAdapter { private final LayoutInflater inflater; public MyAdapter(Context context) { inflater = LayoutInflater.from(context); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (null == convertView) { T binding = getBinding(inflater, parent); holder = new ViewHolder(binding); convertView = binding.getRoot(); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } handleData(position, holder.binding); return convertView; } protected abstract void handleData(int position, T binding); protected abstract T getBinding(LayoutInflater inflater, ViewGroup parent); class ViewHolder { private final T binding; public ViewHolder(T binding) { this.binding = binding; } } }
public class TestAdapter extends MyAdapter<AdapterTestBinding> { private List<String> datas; public TestAdapter(List<String> datas, Context context) { super(context); this.datas = datas; } @Override public int getCount() { return datas.size(); } @Override public Object getItem(int i) { return i; } @Override public long getItemId(int i) { return i; } @Override protected void handleData(int position, AdapterTestBinding binding) { binding.tvContent.setText(datas.get(position)); } @Override protected AdapterTestBinding getBinding(LayoutInflater inflater, ViewGroup parent) { return AdapterTestBinding.inflate(inflater, parent, false); } }
四、其他
如果佈局中有使用 <include> 標簽,需要給 <include> 設置id,才可以獲取到組合控件中的元素。
<!-- 一個簡單的標題欄佈局 --> <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/iv_back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/ic_launcher"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tv_title" android:text="this is title"/> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:orientation="vertical"> <!-- 使用組合控件 --> <include layout="@layout/view_title" android:id="@+id/view_title"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/tv_content" android:text="test"/> </LinearLayout>
public class TestFragment extends BaseFragment<FragmentTestBinding>{ @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); binding.tvContent.setText("this is test"); //通過 include 的id找到對應的控件 binding.viewTitle.tvTitle.setText("this is title"); } @Override protected FragmentTestBinding getBinding(LayoutInflater inflater, ViewGroup container) { return FragmentTestBinding.inflate(inflater, container, false); } }
以上就是Android ViewBinding的使用詳解的詳細內容,更多關於Android ViewBinding的使用的資料請關註WalkonNet其它相關文章!
推薦閱讀:
- None Found