赞
踩
转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/120751996
本文出自【赵彦军的博客】
View Binding是Android Studio 3.6推出的新特性,目的是为了替代findViewById(内部实现还是使用findViewById)。。在启动视图绑定后,系统会为改模块中的每个xml文件生成一个绑定类,绑定类的实例包含对在相应布局中具有 ID 的所有视图的直接引用。
View Binding 的优点
android {
buildFeatures {
viewBinding true
}
}
如果想在生成绑定类时忽略某个布局文件,将 tools:viewBindingIgnore="true"
属性添加到相应布局文件的根视图中:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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" tools:viewBindingIgnore="true" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
为用视图绑定功能后,系统会为该模块中包含的每个 XML 布局文件生成一个绑定类。这个类的类名是以xml布局文件名去掉下换线后,单词首字母大写加上Binding命名的。如 activity_main.xml
生成的类 ActivityMainBinding.
第一步:调用生成的绑定类中包含的静态 inflate() 方法。此操作会创建该绑定类的实例以供 Activity 使用。
第二步:通过调用 getRoot() 方法或使用 Kotlin 属性语法获取对根视图的引用。
第三步:将根视图传递到 setContentView(),使其成为屏幕上的活动视图。
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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" tools:context=".MainActivity"> <TextView android:id="@+id/tv" android:layout_width="100dp" android:layout_height="100dp" android:background="#77f" android:text="赵彦军" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
使用:
class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //关键代码 binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) //获取控件 binding.tv.setOnClickListener { Toast.makeText(this, "hahha", Toast.LENGTH_SHORT).show() } } }
如何在 Fragment 中使用视图绑定 请在 Fragment 的 onCreateView()方法中执行以下步骤(注意:Fragment 的存在时间比其视图长。请务必在 Fragment 的 onDestroyView() 方法中清除对绑定类实例的所有引用。)
调用生成的绑定类中包含的静态 inflate() 方法。此操作会创建该绑定类的实例以供 Fragment 使用。
通过调用 getRoot() 方法或使用 Kotlin 属性语法获取对根视图的引用。
从 onCreateView() 方法返回根视图,使其成为屏幕上的活动视图
//fragment_my.xml <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="40dp" android:text="这是Fragment按钮" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="40dp" android:gravity="center" android:text="这是FragmentTextView" app:layout_constraintBottom_toTopOf="@+id/button" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
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
//在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; }
Activity 基类设计
//Java public class BaseActivity<T extends ViewBinding> 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<ActivityMainBinding> { @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<T : ViewBinding> : 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<ActivityMainBinding>() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding.textView.text = "这是MainActivity" } }
Fragment 基类设计
//Java public class BaseFragment<T extends ViewBinding> 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<FragmentMainBinding>{ @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<T:ViewBinding>: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<FragmentFirstBinding>() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.textView.text = "这是FirstFragment" } }
Activity 基类设计
abstract class BaseActivity<T : ViewBinding> : 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<ActivityMainBinding>() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding.textView.text = "这是MainActivity" } override fun getViewBinding() = ActivityMainBinding.inflate(layoutInflater) }
Fragment 基类设计
abstract class BaseFragment<T : ViewBinding> : 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<FragmentFirstBinding>() { 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) }
方式一:
lass MyItemRecyclerViewAdapter( private val values: List<PlaceholderItem> ) : RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( FragmentItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = values[position] holder.idView.text = item.id holder.contentView.text = item.content } override fun getItemCount(): Int = values.size class ViewHolder(binding: FragmentItemBinding) : RecyclerView.ViewHolder(binding.root) { val idView: TextView = binding.itemNumber val contentView: TextView = binding.content } }
方式二:
class MyItemRecyclerViewAdapter( private val values: List<PlaceholderItem> ) : RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( FragmentItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = values[position] holder.binding.itemNumber.text = item.id } override fun getItemCount(): Int = values.size class ViewHolder(val binding: FragmentItemBinding) : RecyclerView.ViewHolder(binding.root) }
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。