Display Interstitial when clicking the home button of ToolBar

0

I tried to implement displaying an interstitial banner on the home button of my activity but it did not work correctly.

I used

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

   if (id == R.id.home){

      if (interstitialAd.isLoaded()) {
          interstitialAd.show();
      }else{
          finish();
      }
   }
}

But this way the banner does not appear in the click, but only when closing the app.

What is the right way to display the banner when you click the home button?

FIXED AND FUNCTIONING QUESTION

OBs: The configuration for displaying the home button I made direct in the manifest, not needing to set the toolbar in the activity itself, simply include the code below to get the action on the home button of the toolbar.

MANIFEST

    <activity
        android:name=".MinhaActivitySecundaria"
        android:screenOrientation="portrait"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:windowSoftInputMode="adjustResize"
        android:parentActivityName=".MainActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".MainActivity" />
    </activity>

INCLUDE THE CODE BELOW IN SECONDARY ACTIVITY

Remember to use the AppCompatActivity extension

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

   if (id == android.R.id.home){

      if (interstitialAd.isLoaded()) {
          interstitialAd.show();
          finish();
      }else{
          finish();
      }
   }
   return true;
}
    
asked by anonymous 27.04.2017 / 23:13

1 answer

2

Henqsan,

You should use the id below that is the correct id for the back button of the activity.

    if (id == android.R.id.home){
         doSomethink();
    }

Remembering that if you are using Toolbar you have an arrow-there.

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    assert getSupportActionBar() != null;
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    
28.04.2017 / 21:43