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

时间:2012-01-04 23:25:16

标签: android android-layout nullpointerexception ads

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

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);

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

 RelativeLayout.LayoutParams rparams = (LayoutParams) mLayout.getLayoutParams();

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" >

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

1 个答案:

答案 0 :(得分:6)

此行发生错误:

mLayout = (RelativeLayout) findViewById(R.layout.main);

findViewById方法的名称非常明显 - 它用于通过ID查找视图,但是您尝试使用布局参考而不是ID引用来查找视图。请尝试以下操作:

mLayout = (RelativeLayout) findViewById(R.id.main);

此外,您的RelativeLayout应包含android:id标记。尝试为RelativeLayout使用以下XML:

<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" >