setBackground空指针异常

时间:2015-06-09 07:29:24

标签: android android-layout

我试图将背景设置为我的活动,但每次都会抛出nullpointer异常

这是我的代码

 super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    RelativeLayout layout  = (RelativeLayout) findViewById(R.layout.activity_main);
    layout.setBackground(getResources().getDrawable(R.drawable.welcome_2));
    if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
            layout.setBackgroundDrawable( getResources().getDrawable(R.drawable.welcome_1) );
            } else { 
                layout.setBackground(getResources().getDrawable(R.drawable.welcome));
            } 
setContentView(R.layout.activity_main);

这是我的布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

2 个答案:

答案 0 :(得分:4)

移动

 setContentView(R.layout.activity_main);

 RelativeLayout layout  = (RelativeLayout) findViewById(R.id.layout);

并在relativelayout

中定义了XML ID
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:id="@+id/layout"
 tools:context=".MainActivity" >

答案 1 :(得分:0)

首先在Xml中为布局赋予id

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/layout"
android:layout_height="match_parent"
tools:context=".MainActivity" >

然后在java代码中使用像这样

 setContentView(R.layout.activity_main);
 RelativeLayout layout  = (RelativeLayout) findViewById(R.id.layout);
 layout.setBackground(R.drawable.welcome_2);