【发布时间】:2016-01-01 18:20:18
【问题描述】:
我正在尝试以编程方式实例化和添加视图对象
RelativeLayout activityMain = (RelativeLayout)findViewById(R.id.activity_main);
View playControlsPanelMinimized = new View(this);
activityMain.addView(playControlsPanelMinimized);
我在 log cat 中得到这个错误
Attempt to invoke virtual method
'void android.widget.RelativeLayout.addView(android.view.View)'
on a null object reference
at com.example.michael.musicplayer.PlayPanel.onBackPressed(PlayPanel.java:50)
这是 onBackPressed() 方法和第 50 行
@Override
public void onBackPressed() {
super.onBackPressed();
// some code
);
RelativeLayout activityMain = (RelativeLayout)findViewById(R.id.activity_main);
View playControlsPanelMinimized = new View(this);
activityMain.addView(playControlsPanelMinimized); // Line # 50
}
这是activity_main.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:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
android:paddingBottom="0dp"
tools:context=".MainActivity"
android:id="@+id/activity_main">
<ListView
android:id="@+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
<RelativeLayout
android:id="@+id/hidden_panel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/listView1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name" />
</RelativeLayout>
</RelativeLayout>
【问题讨论】:
-
R.id.activity_main是布局,而不是视图,因此您的findViewById(R.id.activity_main);将返回 null。您必须改用布局膨胀。 -
@the_pole 好吧,我的错。如果我们膨胀了布局,那么我们可以使用 findViewById 来获取它。
-
如果你的布局被夸大了,那么你应该没问题。您是否尝试将 mainActivity 声明为类私有变量并在您的 onCreate() 方法中而不是在 onBackPressed 事件中实例化它?
-
我猜不是。我已经创建了一个测试项目,并且可以随时向其中添加新元素。
-
我发布的代码没有出错。新视图已成功添加到主要活动中
标签: android