什么是View Binding
官方文档
View Binding是Android Studio 3.6推出的新特性,目的是为了替代findViewById(内部实现还是使用findViewById)。。在启动视图绑定后,系统会为改模块中的每个xml文件生成一个绑定类,绑定类的实例包含对在相应布局中具有 ID 的所有视图的直接引用。
View Binding 的优点
- Null 安全:由于视图绑定会创建对视图的直接引用,因此不存在因视图 ID 无效而引发 Null 指针异常的风险。此外,如果视图仅出现在布局的某些配置中,则绑定类中包含其引用的字段会使用
@Nullable
标记。 - 类型安全:每个绑定类中的字段均具有与它们在 XML 文件中引用的视图相匹配的类型。这意味着不存在发生类转换异常的风险。
如何启用View Binding 功能
android {
...
viewBinding {
enabled = true
}
}
}
如果想在生成绑定类时忽略某个布局文件,将 tools:viewBindingIgnore="true"
属性添加到相应布局文件的根视图中:
怎么去使用View Binding
为用视图绑定功能后,系统会为该模块中包含的每个 XML 布局文件生成一个绑定类。这个类的类名是以xml布局文件名去掉下换线后,单词首字母大写加上Binding命名的。如activity_main.xml生成的类ActivityMainBinding.
-
如何在Activity中设置绑定,请在 Activity 的 onCreate() 方法中执行以下步骤:
调用生成的绑定类中包含的静态
inflate()
方法。此操作会创建该绑定类的实例以供 Activity 使用。通过调用
getRoot()
方法或使用 Kotlin 属性语法获取对根视图的引用。将根视图传递到 setContentView(),使其成为屏幕上的活动视图。
//activity_main.xml
//MainActivity.java public class MainActivity extends AppCompatActivity { private ActivityMainBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //关键代码 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","点击了按钮"); } }); } }
-
如何在 Fragment 中使用视图绑定 请在 Fragment 的 onCreateView()方法中执行以下步骤(注意:Fragment 的存在时间比其视图长。请务必在 Fragment 的 onDestroyView() 方法中清除对绑定类实例的所有引用。)
调用生成的绑定类中包含的静态
inflate()
方法。此操作会创建该绑定类的实例以供 Fragment 使用。通过调用
getRoot()
方法或使用 Kotlin 属性语法获取对根视图的引用。-
从
onCreateView()
方法返回根视图,使其成为屏幕上的活动视图。如果view已经创建可以在onViewCreated()中使用bind(view)方法。官方示例
//fragment_my.xml
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", "点击了按钮"); } }); } @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", "点击了按钮"); } }); } @Override public void onDestroy() { super.onDestroy(); binding = null; }
使用View Binding 写的基类
- 通过反射的方式
//Java public class BaseActivity
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 { @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","点击按钮"); } }); } }
//Kotlin
open class BaseActivity : AppCompatActivity() {
protected lateinit var binding: T
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val type = javaClass.genericSuperclass as ParameterizedType
val aClass = type.actualTypeArguments[0] as Class<*>
val method = aClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
binding = method.invoke(null, layoutInflater) as T
setContentView(binding.root)
}
}
class MainActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding.textView.text = "这是MainActivity"
}
}
//Java
public class BaseFragment 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{
@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","点击按钮");
}
});
}
}
//Kotlin
open class BaseFragment:Fragment(){
lateinit var binding: T
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val type = javaClass.genericSuperclass as ParameterizedType
val aClass = type.actualTypeArguments[0] as Class<*>
val method = aClass.getDeclaredMethod("inflate", LayoutInflater::class.java,ViewGroup::class.java,Boolean::class.java)
binding = method.invoke(null,layoutInflater,container,false) as T
return binding.root
}
}
class FirstFragment : BaseFragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.textView.text = "这是FirstFragment"
}
}
2.不通过反射的方式
abstract class BaseActivity : AppCompatActivity() {
private lateinit var _binding: T
protected val binding get() = _binding;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = getViewBinding()
setContentView(_binding.root)
}
protected abstract fun getViewBinding(): T
}
class MainActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding.textView.text = "这是MainActivity"
}
override fun getViewBinding() = ActivityMainBinding.inflate(layoutInflater)
}
abstract class BaseFragment : Fragment() {
private lateinit var _binding: T
protected val binding get() = _binding;
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = getViewBinding(inflater, container)
return _binding.root
}
protected abstract fun getViewBinding(inflater: LayoutInflater, container: ViewGroup?): T
}
class FirstFragment : BaseFragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.textView.text = "这是FirstFragment"
}
override fun getViewBinding(
inflater: LayoutInflater,
container: ViewGroup?
) = FragmentFirstBinding.inflate(inflater, container, false)
}