Android ViewBinding的使用 Android ViewBinding的使用详解
一条鱼和一片海 人气:1最近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); } }
加载全部内容