2014-05-20 122 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);