Java – How is R.id used in Android Studio in general?

How is R.id used in Android Studio in general?… here is a solution to the problem.

How is R.id used in Android Studio in general?

I inherited all my activities and fragments from the base activity and base fragment.

I want to centralize some behaviors across applications and create some separate git repositories for them.

One convention is that every activity and fragment should have a main ProgressBar embedded anywhere in the XML layout, and its id is simply progress.

The problem is that the ProgressBar class is defined in another git repository, while the actual XML is defined in a different git repository. So I can’t access R.id.progress in my code.

I have this code in my BaseActivity:

public class BaseActivity extends AppCompatActivity {

ProgressBar progress;

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            progress = findViewById(R.id.progress);  this line is red
        } catch (Exception ex) {
             notifying error
        }
    }

public void showProgress() {
         showing progress
    }

public void hideProgress() {
         hiding
    }
}

So, in all my activities, I simply call showProgress() whenever needed;

How do I fix this?

Solution

If your BaseActivity resides in a base module (let’s call it a BaseActivity Module) and the actual activity and xml are in another module (we call it an Activity module), it depends on the BaseActivity module of the hierarchy like this :

 Activity Module
   -- BaseActivity module

You can then create an xml file containing R.id.progress as a temporary ID in BaseActivity.

When you use Create a subclass from a BaseActivity, the subclass Activity has xml that contains R.id.progress. Your activity will use R.id.progress in xml instead of BaseActivity.

Note that each XML with a specific name can be overwritten by adding an XML with the same name. For example, if you have an view_progress.xml in a BaseActivity module, it will be overwritten by an view_progress.xml in the Activity module.

Related Problems and Solutions