简体   繁体   中英

How to set the android background and keep the admob advertisement visible

I have a android application that is using fragments. It has approximately two items in the menu bar. The first activity (main activity is working fine.) When I switch to the second tab, everything is working fine. Then when I try to change the background to black on my second fragment Activity I lose my advertisement. If I click where the advertisement "should be" it opens my browser so the ad is still there, just is not visible anymore.

When I remove "android:background="@android:color/black" from the "activity_contact.xml", my advertisement becomes visible again. Why is this happening, and how can I change the background for my fragment activity and keep my admob ad visible? I also have been breaking my neck in an attempt to get "View getView()" to work for my ArrayAdapter, but it just will not work. I've tried with and without "@Override". Is this because I'm using a fragment?

Any help is appreciated.

MainActivity.jar/

package com.books4nooks.tashasays;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.annotation.TargetApi;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;

public class MainActivity extends FragmentActivity implements
        ActionBar.OnNavigationListener {

    /**
     * The serialization (saved instance state) Bundle key representing the
     * current dropdown position.
     */
    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
    private AdView adView;
    private static final String AD_UNIT_ID = "xxx";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Create the adView.
        adView = new AdView(this);
        adView.setAdUnitId(AD_UNIT_ID);
        adView.setAdSize(AdSize.SMART_BANNER);

        // Add the AdView to the view hierarchy. The view will have no size
        // until the ad is loaded.

        RelativeLayout layout = (RelativeLayout) findViewById(R.id.container);


        layout.addView(adView);

        // Create an ad request. Check logcat output for the hashed device ID to
        // get test ads on a physical device.
        AdRequest adRequest = new AdRequest.Builder()
            .build();

        // Start loading the ad in the background.
        adView.loadAd(adRequest);

        // Set up the action bar to show a dropdown list.
        final ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);


        // Set up the dropdown list navigation in the action bar.
        actionBar.setListNavigationCallbacks(
        // Specify a SpinnerAdapter to populate the dropdown list.
                new ArrayAdapter<String>(getActionBarThemedContextCompat(),
                        android.R.layout.simple_list_item_1,
                        android.R.id.text1, new String[] {
                                getString(R.string.title_section1),
                                getString(R.string.title_section2),
                                 }), this);
    }

      @Override
      public void onResume() {
        super.onResume();
        if (adView != null) {
          adView.resume();
        }
      }

      @Override
      public void onPause() {
        if (adView != null) {
          adView.pause();
        }
        super.onPause();
      }

      /** Called before the activity is destroyed. */
      @Override
      public void onDestroy() {
        // Destroy the AdView.
        if (adView != null) {
          adView.destroy();
        }
        super.onDestroy();
      }

    /**
     * Backward-compatible version of {@link ActionBar#getThemedContext()} that
     * simply returns the {@link android.app.Activity} if
     * <code>getThemedContext</code> is unavailable.
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    private Context getActionBarThemedContextCompat() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            return getActionBar().getThemedContext();
        } else {
            return this;
        }
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        // Restore the previously serialized current dropdown position.
        if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
            getActionBar().setSelectedNavigationItem(
                    savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // Serialize the current dropdown position.
        outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
                .getSelectedNavigationIndex());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);               
        return true;
    }

    @Override
      public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        // action with ID action_settings was selected
        case R.id.action_settings:
          finish();
          android.os.Process.killProcess(android.os.Process.myPid());
          super.onDestroy();
          break;
        default:
          break;
        }

        return true;
      } 

    @Override
    public boolean onNavigationItemSelected(int position, long id) {
        // When the given dropdown item is selected, show its contents in the
        // container view.
        Fragment fragment = new DummySectionFragment();
        Bundle args = new Bundle();
        args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
        fragment.setArguments(args);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, fragment).commit();
        return true;
    }


    /**
     * A dummy fragment representing a section of the app, but that simply
     * displays dummy text.
     */
    public static class DummySectionFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        public static final String ARG_SECTION_NUMBER = "section_number";
        private RSSFeed myRssFeed = null;

        List headlines;
        List links;
        ListView getListText;
        TextView feedTitle;
        TextView feedDescribtion;
        TextView feedPubdate;
        TextView feedLink;
        View rootView;


        public DummySectionFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);

            TextView dummyTextView = (TextView) rootView
                    .findViewById(R.id.section_label);
            dummyTextView.setText(Integer.toString(getArguments().getInt(
                    ARG_SECTION_NUMBER)));
            if (dummyTextView.getText().equals("1"))
            {
                rootView = inflater.inflate(R.layout.activity_main, container, false);
                setRetainInstance(true);
                startReadRss();
            }

            if (dummyTextView.getText().equals("2"))
            {
                rootView = inflater.inflate(R.layout.activity_contact, container, false);
                setRetainInstance(true);
                Button btnSubmit = (Button) rootView.findViewById(R.id.button1);                    

                btnSubmit.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(final View v)
                    {
                        View getBodyLayout = (View)getView().findViewById(R.id.emailBody); //Find the layout
                        EditText getBodyText = (EditText) getBodyLayout.findViewById(R.id.emailBody); //Access the object from the layout
                        String gotBodyText = getBodyText.getText().toString(); //Get value and convert to a string
                        sendContact(rootView, gotBodyText);
                    }
                    });
            }

            return rootView;
        }

        public boolean isNetworkAvailable() {
            ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        }

        public class RssLoadingTask extends AsyncTask<Void, Void, Void> {

            @Override
            protected void onPostExecute(Void result) {
                // TODO Auto-generated method stub
                displayRss();
            }

            @Override
            protected void onPreExecute() {
                // TODO Auto-generated method stub
                preReadRss();
            }

            @Override
            protected void onProgressUpdate(Void... values) {
                // TODO Auto-generated method stub
                //super.onProgressUpdate(values);
            }

            @Override
            protected Void doInBackground(Void... arg0) {
                // TODO Auto-generated method stub
                readRss();
                return null;
            }

        }

        public InputStream getInputStream(URL url)
        {
            try
            {
                return url.openConnection().getInputStream();
            }
            catch (IOException e)
            {
                return null;
            }
        }

         private void startReadRss(){
             if (isNetworkAvailable())
                new RssLoadingTask().execute();
             else
                 Toast.makeText(getActivity(), "Sorry, your internet connection is currently available.", Toast.LENGTH_SHORT).show();
               }

           private void preReadRss()
           {

               Toast.makeText(this.getActivity(), "Reading RSS, Please wait.", 0).show();
           }

           private void readRss(){

            // Initializing instance variables
               headlines = new ArrayList();
               links = new ArrayList();

               try {
                    URL url = new URL("http://msn.com/feed/");

                    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                    factory.setNamespaceAware(false);
                    XmlPullParser xpp = factory.newPullParser();

                    //Retrieve the XML from an input stream
                    xpp.setInput(getInputStream(url), "UTF_8");

                    boolean insideItem = false;

                    //Returns the type of current event: START_TAG, END_TAG, etc..

                    int eventType = xpp.getEventType();

                    while (eventType != XmlPullParser.END_DOCUMENT) {
                        if (eventType == XmlPullParser.START_TAG) {

                            if (xpp.getName().equalsIgnoreCase("item")) {
                                insideItem = true;
                            }
                            else if (xpp.getName().equalsIgnoreCase("title")) {
                                if (insideItem)
                                    headlines.add(xpp.nextText()); //extract the headline
                            }
                            else if (xpp.getName().equalsIgnoreCase("link")) {
                                if (insideItem)
                                    links.add(xpp.nextText());
                            }
                        } else if (eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")) {
                            insideItem = false;
                        }
                        eventType = xpp.next(); //move to next element
                    }


         } catch (MalformedURLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
         } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
           }

           private void displayRss(){

            // Binding data
               ArrayAdapter adapter = new ArrayAdapter<String>(getActivity(), R.layout.customlist, headlines);
                View getListLayout = (View)getView().findViewById(R.id.lView); //Find the layout
                getListText = (ListView) getListLayout.findViewById(R.id.lView); //Access the object from the layout
                getListText.setAdapter(adapter);

                   getListText.setOnItemClickListener(new OnItemClickListener() {
//
                                @Override
                                public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
                                    Uri uri = Uri.parse((String) links.get(position));
                                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                    startActivity(intent);
                               }
                               });
            }

        public void sendContact(View view, String emailBody)
        {

            Intent sendEmail = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", "admin@msn.com", null));
            sendEmail.putExtra(Intent.EXTRA_SUBJECT, "Subject line");
            sendEmail.putExtra(Intent.EXTRA_TEXT, emailBody);
            try {
            startActivity(Intent.createChooser(sendEmail, "Send e-mail."));
            }
            catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(getActivity(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

activity_contact.xml/

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="xxx" >
    </com.google.android.gms.ads.AdView>

    <EditText
        android:id="@+id/txtName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/adView"
        android:layout_marginTop="25dp"
        android:ems="10"
        android:hint="Enter your name." >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/emailBody"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/txtName"
        android:layout_marginTop="34dp"
        android:ems="10"
        android:hint="Enter your message."
        android:inputType="textMultiLine"
        android:maxLines="7" />

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/emailBody"
        android:text="Submit" />

</RelativeLayout>

activity_main.xml/

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="xxxx" >

</com.google.android.gms.ads.AdView>

<ListView
android:id="@+id/lView"
android:layout_below="@+id/adView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"    />

I just came across this question:

Android AdMob: addView doesn't show ad until return to activity

Try using mAdView.bringToFront() in onAdLoaded(). Hopefully that will pull the adview above the background and make it redraw.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM