Is it safe to pass an instance of an Activity to another object?

Basically, I'm trying to pass an instance of my Activity to another object that will create a dynamic interface.

The main reason I do this is to keep the Activity class clean.

Are there any consequences to this? Will this affect garbage collection and cause a memory leak?

Here is an example of what I am doing:

Activity:

/* uses the instance of the Activity to build Views which are loaded from XML files (for non technical users to add content */ ContentHelper ch = new ContentHelper(MyActivity.this); 

Should I keep the dynamic building of the View as part of the Activity, or is it okay to pass the instance to other classes for this?

If I store it in an Activity, it just feels bloated to me and is much more difficult to manage.

+4
source share
1 answer

In my opinion, it’s nice to transfer ACTIVITY somewhere - in fact, I'm not sure if this will be done at all.

What can you do:

1 - You can create your own class by expanding the View class, creating your own interface. What you need to pass to this class is your activity context!

eg:

 class Custom_UI_Builder extends View { public Custom_UI_Builder(Context cxt) { super(cxt); // more stuff - your UI components... } } 

in Activity that uses your UI class

 public myActivity extends Activity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); myView = new Custom_UI_Builder(this); //what every else you need... mainLayout = new LinearLayout(this.getApplicationContext()); mainLParam = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); mainLayout.setLayoutParams(mainLParam); mainLayout.setOrientation(LinearLayout.VERTICAL); mainLayout.addView(myView, LayoutParams.MATCH_PARENT, 390); setContentView(mainLayout); }} 

2 - Then you can create an instance of the custom_UI_builder class in your activity.

I'm not sure if this will have undesirable effects when loading memory.

Hope it works!

+3
source

Source: https://habr.com/ru/post/1335069/


All Articles