Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 836
Danail Avatar asked Jan 09 '12 15:01

Danail


2 Answers

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.

like image 150
Saurabh Verma Avatar answered Oct 18 '22 10:10

Saurabh Verma


Why don't you use Fragments?

http://developer.android.com/guide/topics/fundamentals/fragments.html

I think your use case is perfect for this.

like image 21
neteinstein Avatar answered Oct 18 '22 09:10

neteinstein