Alex Rivera | Logout

Android: Reusing same View object in different Activities (the case is about ad banners)

Asked 2012-01-09T15:03:11.740
14

I want to reuse the same view object (not the view class, or the xml file, I mean the object in the memory) in different Activities.

I almost had this done. The thing is, of course, the context.

I tried with the application context. It almost worked, but then when I click on the view I am transmitting between different activities, and try to start another application from it (or link) it crashed. (I don't remember the exact crash, but I'll dig it, if you need it).

I tried with some activity, that I didn't mind leaking once, and giving it as a Context. It worked, actually everything worked, until I began to get weird exceptions in ViewFlipper.

My question is, is this reusing really possible, and how to do it stable? Have you got any experience with that?

Thanks A LOT in advance, Dan

Edit
Report

2 Answers

6

I'm keeping in mind that you can afford to leak 1 activity, as this is the only solution I know: Declare a static view, say myAdView in your 1st activity (in which you are requesting ad). Now you can ad and remove this myAdView in every activity transation. Ofcource you will have to maintain seperate LinearLayouts for ur ads in seperate activities, where we will add/remove the myAdView eg. Suppose you are going from activity A to B, then in A's onPause remove myAdView:

private LinearLayout layoutAd;
layoutAd = (LinearLayout) findViewById(R.id.layout_ad); // from A's xml
protected void onPause() {
    super.onPause();
    layoutAd.removeView(FirstActivity.adBannerView);
}

and in B's onResume add the same (FirstActivity's) myAdView:

private LinearLayout layoutAd;
layoutAd = (LinearLayout) findViewById(R.id.layout_ad);  // from B's xml
protected void onResume() {
      super.onResume();
      layoutAd.addView(FirstActivity.adBannerView);
}

Hope this solves your problem to some extent.

answered 2012-01-13T10:23:54.753
-1

If you want a variable to be used within multiple activities then best practice for it is to put them in a separate class (can be named as Constants or MyVars) as static variable and use them in any activity you want as like Constants.SavedVar or MyVars.SavedVar as below is code example.

public class MyStaticVars {

public static Context myContext;
}

// First Activity where you want to save a specific context

MyStaticVars.myContext = ContextToBeSaved;

// Any Other Activity where you want to reuse that context

priviousContext = MyStaticVars.myContext;
answered 2012-01-09T15:22:13.363

Your Answer