Android JetPack学习总结(十七)

View Binding

比DataBinding轻量;比Kotlin Synthetics安全。

在gradle(app)中开启ViewBinding:

viewBinding {
    enable true
}

和dataBinding一样,需要使用自动生成的ActivityBinding对象:

    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding=ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
    }
}

之后就可以直接使用binding来获取这个视图中的组件了:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding=ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.textView.setText("view");
        binding.textView2.setText("binding");
    }

同理,在fragment中也是如此:

public class BlankFragment extends Fragment {
    private FragmentBlankBinding binding;

//...

  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding=FragmentBlankBinding.inflate(getLayoutInflater());
        
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding.textView4.setTextSize(30f);
        binding.textView4.setText("from fragment layout");
    }
}

发表评论