Android: automatically make variables for all IDs in xml

Since version 3.6 of android studio they have officially added the support of autometically view binding that's generates a binding class for each XML layout file. These classes contain direct references to all views that have an ID in the corresponding layout.

you can enable it by modifying your build.gradle file.

android {
  ...
  viewBinding {
      enabled = true
  }
}

If view binding is enabled for a module, a binding class is generated for each XML layout file that the module contains. Each binding class contains references to the root view and all views that have an ID.

For example, given a layout file called result_profile.xml The generated binding class will be called ResultProfileBinding.

Example:

private ResultProfileBinding binding;

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

Please check the official documentation here.


Try using Android Annotations. It provides useful annotations to replace boilerplate code.

For instance, see @ViewById documentation: just declare the fields annotated

@ViewById
EditText myEditText;

@ViewById(R.id.myTextView)
TextView textView;

It replaces

EditText myEditText;

TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
    [...]
    myEditText = (EditText) findViewById(R.id.myEditText);
    textView = (TextView) findViewById(R.id.myTextView);
}

I made a tool to automatically generate the Java code for tying layout XML's and program logic together.

Basically it takes an XML layout, and generates all the necessary Java code for you in an instant. There is support for basic member variables, ViewHolder pattern, ArrayAdapter, CursorAdapter and RoboGuice code types.

You can find it here: Android Layout Finder | Buzzing Android