2015-06-09 3 views
-2

им пытается установить фон для моей деятельности, но он бросает NullPointer исключения каждый разsetBackground нулевого указателя исключение

вот мой код

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

ответ

4

движения

setContentView(R.layout.activity_main); 

перед тем

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

и определены relativelayout Id в XML

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

Во-первых, дать идентификатор для макета в Xml

<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); 
Смежные вопросы