SpoocyCrep
SpoocyCrep

Reputation: 614

Hiding and showing Adview

I have a Surfaceview and an AdView, I drew the Adview like that:

    g=new GameView(this );
    setContentView(R.layout.activity_game);
    RelativeLayout layout = (RelativeLayout)findViewById(R.id.vMain);
    layout.addView(g);
     mAdView = new AdView(this); 
    mAdView.setAdSize(AdSize.BANNER);
    mAdView.setAdUnitId(myId);
    AdRequest adRequest = new AdRequest.Builder()
        .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
        .build(); 
    if(mAdView.getAdSize() != null || mAdView.getAdUnitId() != null)
    mAdView.loadAd(adRequest); 
    ((RelativeLayout)findViewById(R.id.vMain)).addView(mAdView  );
    mAdView.bringToFront();
     mAdView.setVisibility(View.GONE);

On top of the Surfaceview, and hide it. Now I want to show it by calling it from the surfaceview, is that possible? I tried creating this function:

public void hide(){
    mAdView.setVisibility(View.GONE);

}
public void show(){
    mAdView.setVisibility(View.VISIBLE);

}

and call it from the surfaceview, but it gave me "Only the original thread that created a view can touch its views.” exception. What do I do?

Upvotes: 1

Views: 415

Answers (1)

Ivan Skoric
Ivan Skoric

Reputation: 1210

I don't know from which thread you've been calling these methods, but all UI updates have to be called from the main thread. Use:

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        // Update you UI here.
    }
});

For example:

public void hide(){
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mAdView.setVisibility(View.GONE);
        }
    });
}

public void show(){
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mAdView.setVisibility(View.VISIBLE);
        }
    });
}

Upvotes: 1

Related Questions