最近Android Studio 升級後 butterknife 有一個警告:java
Resource IDs will be non-final in Android Gradle Plugin version 5.0, avoid using them as annotation attributesandroid
查看官網發現:markdown
butterknife已經棄用,建議使用 view binding 替換。app
官方介紹:ide
經過視圖綁定功能,您能夠更輕鬆地編寫可與視圖交互的代碼。在模塊中啓用視圖綁定以後,系統會爲該模塊中的每一個 XML 佈局文件生成一個綁定類。綁定類的實例包含對在相應佈局中具備 ID 的全部視圖的直接引用。oop
在大多數狀況下,視圖綁定會替代 findViewById。佈局
android {
...
viewBinding {
enabled = true
}
buildFeatures {
viewBinding = true
}
}
複製代碼
在 Activity 的 onCreate() 方法中執行如下步驟:gradle
private ResultProfileBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ResultProfileBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
}
複製代碼
如今便可使用該綁定類的實例來引用任何視圖:ui
binding.getName().setText(viewModel.getName());
binding.button.setOnClickListener(new View.OnClickListener() {
viewModel.userClicked()
});
複製代碼
在 Fragment 的 onCreateView() 方法中執行如下步驟:this
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;
}
複製代碼
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
中的重複代碼。
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();
}
複製代碼
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());
}
}
複製代碼
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);
}
}
複製代碼
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);
}
}
複製代碼