2012-01-04 107 views
2

我希望此相對佈局最終會在底部加載廣告。爲什麼會這樣空指針在引用主佈局時出現異常

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

任何想法:

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的佈局發生H ERE?

回答

6

錯誤發生在這條線:

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

這是由findViewById方法的名稱很明顯 - 它用於查找其ID的觀點,但你要找到使用視圖佈局引用,而不是ID引用。試着用以下:

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

此外,您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" >