我以编程方式编写了一个布局。当我尝试用XML实现它时,我无法使它工作。它与NullPointerException崩溃,我真的不知道为什么。
这是我的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 :(得分:0)
您尚未将xml布局的内容设置到屏幕,而您正在查找ImageView的ID。这导致了NPE。
canal1 = (ImageView) findViewById(R.id.canal_1);
上述语句将导致nullpointerexception,因为您尚未设置布局,并且您正在尝试查找xml文件中定义的id格式。
@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>