viewbinding

2022-06-21  本文已影响0人  闫鹏飞写字的地方

官方地址:https://developer.android.google.cn/topic/libraries/view-binding

B站地址:https://www.bilibili.com/video/BV1fY4y1i7BG?p=8&vd_source=c9e619eb6c2ba53337eccc49eb025732

android {
        ...
        viewBinding {
            enabled = true
        }
    }
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        binding.tvTest.text = "Hello BeiJing"
    }
}

Binding文件位置


image.png

ActivityMainBinding

public final class ActivityMainBinding implements ViewBinding {
  @NonNull
  private final ConstraintLayout rootView;

  @NonNull
  public final TextView tvTest;

  private ActivityMainBinding(@NonNull ConstraintLayout rootView, @NonNull TextView tvTest) {
    this.rootView = rootView;
    this.tvTest = tvTest;
  }

  @Override
  @NonNull
  public ConstraintLayout getRoot() {
    return rootView;
  }

  @NonNull
  public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater) {
    return inflate(inflater, null, false);
  }

  @NonNull
  public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater,
      @Nullable ViewGroup parent, boolean attachToParent) {
    View root = inflater.inflate(R.layout.activity_main, parent, false);
    if (attachToParent) {
      parent.addView(root);
    }
    return bind(root);
  }

  @NonNull
  public static ActivityMainBinding bind(@NonNull View rootView) {
    // The body of this method is generated in a way you would not otherwise write.
    // This is done to optimize the compiled bytecode for size and performance.
    int id;
    missingId: {
      id = R.id.tvTest;
      TextView tvTest = ViewBindings.findChildViewById(rootView, id);
      if (tvTest == null) {
        break missingId;
      }

      return new ActivityMainBinding((ConstraintLayout) rootView, tvTest);
    }
    String missingId = rootView.getResources().getResourceName(id);
    throw new NullPointerException("Missing required view with ID: ".concat(missingId));
  }
}

上一篇下一篇

猜你喜欢

热点阅读