viewBinding基础使用(好使)

android {
        ...
        viewBinding {
            enabled = true
        }
    }

如果您希望在生成绑定类时忽略某个布局文件,请将 tools:viewBindingIgnore="true" 属性添加到相应布局文件的根视图中:


        ...
    

使用

为某个模块启用视图绑定功能后,系统会为该模块中包含的每个 XML 布局文件生成一个绑定类。每个绑定类均包含对根视图以及具有 ID 的所有视图的引用。系统会通过以下方式生成绑定类的名称:将 XML 文件的名称转换为驼峰式大小写,并在末尾添加“Binding”一词。

activity

比如的布局叫activity_main,生成的bingding名称就是 ActivityMainBinding

public class MainActivity2 extends AppCompatActivity  {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
        LinearLayout root = binding.getRoot();
        setContentView(root);
        binding.hwDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity2.this,"del",Toast.LENGTH_SHORT).show();
            }
        });       

    }

fragment

布局名称为 fragment_blank,这里有个注意点,如果直接用标签类型导入fragment,fragment也要加个id。


public class BlankFragment extends Fragment {
    private FragmentBlankBinding binding;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentBlankBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding.btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.textFragment.setText(new Random().nextInt(1000) + "");
            }
        });
    }

Adapter 使用

class ViewBindAdapter extends RecyclerView.Adapter {


    @NonNull
    @NotNull
    @Override
    public ViewBindHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        ItemRecycleBinding binding = ItemRecycleBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new ViewBindHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull ViewBindHolder holder, int position) {
        holder.binding.tvButtom.setText("");

    }

    @Override
    public int getItemCount() {
        return 0;
    }


    static class ViewBindHolder extends RecyclerView.ViewHolder {


        public ItemRecycleBinding binding;
        
        public ViewBindHolder(@NonNull @NotNull ItemRecycleBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }


    }
}

你可能感兴趣的:(viewBinding基础使用(好使))