0

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

我不知道为什么这会失败。在我看来,一切都应该运行良好。

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

亲切的问候,劳尔

4

1 回答 1

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>
于 2013-04-21T11:09:53.860 回答