2013-04-21 83 views
0

我已經以編程方式編寫了我的佈局之一。當我嘗試在XML中實現它時,我無法使其工作。它崩潰與NullPointerException,我真的不知道爲什麼。使用XML元素以編程方式創建佈局

這是我的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:orientation="vertical" 
tools:context=".DisplayMessageActivity" > 

<ImageView 
    android:id="@+id/canal_1" 
    android:contentDescription="@string/desc" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentBottom="true" 
    android:onClick="canal1_Click" 
    android:src="@drawable/pestanya_seleccionada" /> 

</RelativeLayout> 

而且我想要的是:

ImageView canal1; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    /* layout prinicpal */ 
    RelativeLayout relativeLayout = new RelativeLayout(this); 
    RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); 
    canal1 = (ImageView) findViewById(R.id.canal_1); 
    relativeLayout.addView(canal1); 
    setContentView(relativeLayout, rlp); 
} 

它崩潰的relativeLayout.addView(canal1);

我不知道爲什麼會失敗。在我腦子裏,一切都應該運行良好。

感謝您的閱讀,希望您能幫助我。)

親切的問候, 勞爾

回答

0

您沒有設置XML佈局到屏幕的內容,你發現了的ImageView的ID。這導致了NPE。

canal1 = (ImageView) findViewById(R.id.canal_1); 

上面的語句會導致空指針異常,因爲你沒有設置佈局和你正在努力尋找ID表單中的XML文件中的定義。

@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activty_main); 
RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout); 
//add other ui elements to the root layout ie RelativeLayout 
} 

<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/relativeLayout"// relative layout id 
android:orientation="vertical" 
tools:context=".DisplayMessageActivity" > 
<ImageView 
android:id="@+id/canal_1" 
android:contentDescription="@string/desc" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_alignParentBottom="true" 
android:onClick="canal1_Click" 
android:src="@drawable/pestanya_seleccionada" /> 
</RelativeLayout> 
相關問題