引用主要布局时的空指针异常 [英] Null Pointer Exception when referencing main layout

查看:217
本文介绍了引用主要布局时的空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这个相对布局在底部最终加载广告。

I want this relative layout to eventually load an ad at the bottom.

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被称为低于

Then the Null Pointer occurs below when mLayout is called

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


E / AndroidRuntime(4066):了java.lang.RuntimeException:无法启动活动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" >

知道为什么这发生在这里?

Any idea why this is happening here?

推荐答案

在此行中出现的错误:

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

这是pretty明显由 findViewById 方法的名称 - 这是用来查找其ID的观点,但你想用来取景一个布局的参考,而不是ID参考。具有以下尝试:

It's pretty obvious by the name of the findViewById method - it's used to find a view by its ID, but you're trying to find a view using a layout reference, not ID reference. Try with the following:

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

另外,你的 RelativeLayout的应包括的android:ID 标记。尝试使用以下XML的 RelativeLayout的

Also, your RelativeLayout should include the android:id tag. Try using the following XML for your 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" >

这篇关于引用主要布局时的空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆