Admob在碎片中的应用。

4

我创建了一个带有appcompact的空项目,尝试向其中添加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;

        }
    }

在"adView = new AdView(getActivity());"这一行中出现了"Unreachable code"错误。
2个回答

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.
< p >在onCreateView结尾处的返回值很好< /p >

谢谢,有趣的事情发生了,我没有看到“return”。 - HelloWorld

1

这是答案...在findViewById之前加上root即可。就这样

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接