使用XML元素以编程方式创建布局

问题描述:

我已经以编程方式编写了我的布局之一。当我尝试在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);

我不知道为什么会失败。在我脑子里,一切都应该运行良好。

感谢您的阅读,希望您能帮助我。)

亲切的问候, 劳尔

您没有设置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>