2014-02-26 46 views
0

我有一个正在使用片段的android应用程序。它在菜单栏中大约有两个项目。第一个活动(主要活动工作正常。)当我切换到第二个选项卡时,一切正常。然后,当我尝试在第二个片段上将背景更改为黑色时,我失去了我的广告。如果我点击广告“应该”的位置,它会打开我的浏览器,所以广告仍然存在,只是不再可见。如何设置android背景并保持admob广告可见

当我从“activity_contact.xml”中删除“android:background =”@ android:color/black“时,我的广告再次变为可见状态。为什么会发生这种情况,以及如何更改我的分段活动的背景并保持我的admob广告可见?我也试图让“View getView()”为我的ArrayAdapter工作,但它只是不会工作。这是因为我使用的是片段?

任何帮助表示赞赏。

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", "[email protected]", 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" /> 

回答