2014-05-20 155 views
4

我創建一個空項目與appcompact和試圖添加到它AdMob廣告塊AdMob添加片段

fragment_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 

    tools:context="com.example.testadmobv.MainActivity$PlaceholderFragment" > 
    <LinearLayout  
     android:id="@+id/layout_admob" 

     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" > 
    </LinearLayout> 
    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/hello_world" /> 

</RelativeLayout> 

MainActivity.java

public static class PlaceholderFragment extends Fragment { 

     public PlaceholderFragment() { 



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

      adView = new AdView(getActivity()); 
      adView.setAdUnitId("MY_AD_UNIT_ID"); 
      adView.setAdSize(AdSize.BANNER); 
       LinearLayout layout = (LinearLayout)rootView.findViewById(R.id.layout_admob); 
      layout.addView(adView); 
       AdRequest adRequest = new AdRequest.Builder().build(); 
       adView.loadAd(adRequest); 
      return rootView; 

     } 
    } 

在線「AD瀏覽=新的AdView(getActivity());「錯誤「無法訪問的代碼」

回答

4

你有

View rootView = inflater.inflate(R.layout.fragment_main, container, 
       false); 
return rootView; // remove this 
adView = new AdView(getActivity()); // this is unreachable coz you have return above. 

onCreateView末的收益是細

+0

謝謝,有趣的事情發生後,沒有看到「迴歸」( – HelloWorld

1

這就是答案......你將在findViewById之前寫的根。這一切都是

AdView mAdView = (AdView) root.findViewById(R.id.adView); 
    AdRequest adRequest = new AdRequest.Builder().build(); 
    mAdView.loadAd(adRequest);