android {
...
viewBinding {
enabled = true
}
}
如果您希望在生成綁定類(lèi)時(shí)忽略某個(gè)布局文件酪惭,請(qǐng)將 tools:viewBindingIgnore="true"
屬性添加到相應(yīng)布局文件的根視圖中:
<LinearLayout
...
tools:viewBindingIgnore="true" >
...
</LinearLayout>
使用
為某個(gè)模塊啟用視圖綁定功能后昂勉,系統(tǒng)會(huì)為該模塊中包含的每個(gè) XML 布局文件生成一個(gè)綁定類(lèi)。每個(gè)綁定類(lèi)均包含對(duì)根視圖以及具有 ID 的所有視圖的引用鼻百。系統(tǒng)會(huì)通過(guò)以下方式生成綁定類(lèi)的名稱(chēng):將 XML 文件的名稱(chēng)轉(zhuǎn)換為駝峰式大小寫(xiě),并在末尾添加“Binding”一詞摆尝。
activity
比如的布局叫activity_main,生成的bingding名稱(chēng)就是 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
布局名稱(chēng)為 fragment_blank温艇,這里有個(gè)注意點(diǎn),如果直接用標(biāo)簽類(lèi)型導(dǎo)入fragment堕汞,fragment也要加個(gè)id勺爱。
<fragment
android:layout_width="match_parent"
android:id="@+id/text_fragment"
android:name="com.leo.tpnsdemos.BlankFragment"
android:layout_height="match_parent"/>
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<ViewBindAdapter.ViewBindHolder> {
@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;
}
}
}
自定義View
//找到對(duì)應(yīng)的View的布局
var binding: ViewProgressBinding =
ViewProgressBinding.inflate(LayoutInflater.from(getContext()), this, true)