当前位置:   article > 正文

Android ViewBinding 使用

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。

设置说明

  1. android studio 必须是3.6及更高版本。
  2. com.android.tools.build:gradle 需要 3.6.0及更高版本。
  3. build.gradle 中启用功能,不同模块要分别设置。
android {
    ...
    viewBinding {
    	enabled = true
    }
        
    buildFeatures {
        viewBinding = true
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

二、基本用法

Activity中使用

在 Activity 的 onCreate() 方法中执行以下步骤:

  1. 调用生成的绑定类中包含的静态 inflate() 方法。
  2. 通过调用 getRoot() 方法获取对根视图的引用。
  3. 将根视图传递到 setContentView(),使其成为屏幕上的活动视图。
    private ResultProfileBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ResultProfileBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

现在即可使用该绑定类的实例来引用任何视图:

binding.getName().setText(viewModel.getName());
binding.button.setOnClickListener(new View.OnClickListener() {
	viewModel.userClicked()
});
  • 1
  • 2
  • 3
  • 4

Fragment 中使用

在 Fragment 的 onCreateView() 方法中执行以下步骤:

  1. 调用生成的绑定类中包含的静态 inflate() 方法。
  2. 通过调用 getRoot() 方法获取对根视图的引用。
  3. 从 onCreateView() 方法返回根视图,使其成为屏幕上的活动视图。
  4. 在 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;
    }
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

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;
    }
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

三、了解源码实现

项目运行后,每个布局文件都会生成对应的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));
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48

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();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

可以对代码稍加改造,减少 ActivityFragmentAdapter 中的重复代码。

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();

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
public class TestActivity extends BaseActivity<ActivityMainBinding>{

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    binding.wv.loadUrl("https://www.baidu.com");
  }

  @Override
  protected ActivityMainBinding getBinding() {
    return ActivityMainBinding.inflate(getLayoutInflater());
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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;
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
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);
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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;
    }
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
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);
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

四、其他

如果布局中有使用 <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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
<?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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
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);
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/319860
推荐阅读
相关标签
  

闽ICP备14008679号