3
votes

Lets say that I have the a layout named activity_main.xml and it has an element:

<TextView
    android:id="@+id/text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

An activity named MainActivity.java. In its' onCreate method, I inflate the above layout using viewBinding, and set text of text view:

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

    binding.textView.setText("some text");
}

Now, if I rename the id of TextView in activity_main.xml, by pressing Shift+F6 to something like @+id/text_view_new, then the reference in onCreate doesn't changed from binding.textView.setText("some text"); to binding.textViewNew.setText("some text");

Is this behaviour a limitation, a bug or am I doing something wrong?

1

1 Answers

0
votes

Is this behaviour a limitation, a bug or am I doing something wrong?

My thoughts about:

  • You doing all as expected
  • I think it's not a bug or a limitation, it's just how it's works. Of course, someone could expect magic and change your "textView" to "textViewNew" in activity and someone could say it's a limitation. It's important to understand how View Binding works and whether it could do such a magic or not.

View Binding mechanism generates additional Java Binding-classes. So the magic happened there during build process - class ActivityMainBinding was generated, there was put public field "textView". After getting instance of this class you can write just "binding.textView".

But after renaming "id" in xml it wouldn't be very smart to change this autogenerated class automatically (and that action has to be done if you want to replace "textView" with "textViewNew"). That's why this change doesn't affect anything in code