引用主布局时出现空指针异常

Zac*_*Nag 2 android ads nullpointerexception android-layout

我希望这种相对布局最终在底部加载广告.

public class Main extends Activity {
RelativeLayout mLayout;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);        
    setContentView(R.layout.main);
    mLayout = (RelativeLayout) findViewById(R.layout.main);  

    ImageView View = new ImageView(this, null);      //example view

    mLayout.addView(View);
Run Code Online (Sandbox Code Playgroud)

然后当调用mLayout时,Null指针发生在下面

 RelativeLayout.LayoutParams rparams = (LayoutParams) mLayout.getLayoutParams();
Run Code Online (Sandbox Code Playgroud)

E/AndroidRuntime(4066): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.name.project/com.name.project.Main}: java.lang.NullPointerException

xml用于布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/lib/com.google.ads"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center" >
Run Code Online (Sandbox Code Playgroud)

知道为什么会发生这种情况吗?

Mic*_*Bak 6

此行中发生错误:

mLayout = (RelativeLayout) findViewById(R.layout.main);
Run Code Online (Sandbox Code Playgroud)

这个findViewById方法的名称非常明显- 它用于通过ID查找视图,但是您尝试使用布局参考而不是ID参考来查找视图.尝试使用以下内容:

mLayout = (RelativeLayout) findViewById(R.id.main);
Run Code Online (Sandbox Code Playgroud)

此外,您RelativeLayout应该包括android:id标签.尝试使用以下XML RelativeLayout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/lib/com.google.ads"
android:id="@+id/main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center" >
Run Code Online (Sandbox Code Playgroud)