如何以编程方式实例化和添加视图对象

时间:2015-10-05 06:49:50

标签: android

我正在尝试以编程方式实例化和添加视图对象

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>

2 个答案:

答案 0 :(得分:1)

请记住,在使用findViewById()之前,您要引用的视图必须已经使用setContentView()或者使用Inflater手动充气。否则你只是得到一个空值,这就是为什么NPE

答案 1 :(得分:1)

  

&#39; void android.widget.RelativeLayout.addView(android.view.View)&#39;   在空对象引用上

检查activityMain是否为空

这样的东西
RelativeLayout activityMain = (RelativeLayout)findViewById(R.id.activity_main);
View playControlsPanelMinimized = new View(this);
if(activityMain != null)
    activityMain.addView(playControlsPanelMinimized); // Line # 50

如果activityMain为空,可能您忘了给视图充气。

在片段中你可以做

@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.name_of_your_fragment, container, false);

    //Some code like
    //rootView.findViewById(...);

    return rootView;
}