Android 7.31-1 binding的使用

阴培
2023-12-01

1.Activity中使用binding

java代码:

public class SettingActivity extends BaseActivity {

    private ActivitySettingBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySettingBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
    
    binding.控件id就可以了
    }
}

2.Fragment中使用binding

一样是先声明,然后初始化,Kotlin因为其非空机制会稍微麻烦一点,不过道理是相同的,可以看看《第一行代码》作者郭霖写的博客kotlin-android-extensions插件也被废弃了?扶我起来

public class RightSettingBrightness extends Fragment {

    private FragmentRightSettingBrightnessBinding binding;


    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        
        binding = FragmentRightSettingBrightnessBinding.inflate(inflater, container, false);
        binding.控件id就可以了
        
        return binding.getRoot();
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}

3.Adapter中使用binding(用到后补充)

 类似资料: