android ViewStub inflate方法抛出nullpointer

时间:2017-05-03 11:48:51

标签: java android nullpointerexception

我正在尝试按照本教程在android中构建仪表板布局:

http://www.technotalkative.com/android-dashboard-design-pattern-implementation/

在本教程中,将创建一个抽象类,它将为按钮定义事件处理程序:Home和Feedback以及其他方法。每个活动都扩展了这个超类,因为必须在每个活动中显示主页和反馈按钮(主/家庭活动除外)

抽象类中定义了此方法,这使得主页/反馈按钮依赖于活动

public void setHeader(String title, boolean btnHomeVisible, boolean btnFeedbackVisible)
    {
      ViewStub stub = (ViewStub) findViewById(R.id.vsHeader);
      View inflated = stub.inflate();

      TextView txtTitle = (TextView) inflated.findViewById(R.id.txtHeading);
      txtTitle.setText(title);

      Button btnHome = (Button) inflated.findViewById(R.id.btnHome);
      if(!btnHomeVisible)
       btnHome.setVisibility(View.INVISIBLE);

      Button btnFeedback = (Button) inflated.findViewById(R.id.btnFeedback);
      if(!btnFeedbackVisible)
       btnFeedback.setVisibility(View.INVISIBLE);
    }

例如,显示仪表板布局的主页活动不需要显示主页按钮,因为它已经是主页活动,但是如果从仪表板打开另一个活动,那么我想制作主页按钮可见如下:

public class Activity_Eclair extends DashBoardActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_eclair);         

           //Passing true in order to make the home button visible
            setHeader(getString(R.string.EclairActivityTitle), true, true);
        }
    }

但是,活动无法打开,因为我总是得到一个NullPointerException并且我不知道原因:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.ViewStub.inflate()' on a null object reference

问题是setHeader-method中的stub变量为null,但我不知道原因:

  ViewStub stub = (ViewStub) findViewById(R.id.vsHeader);
  View inflated = stub.inflate()

1 个答案:

答案 0 :(得分:0)

我发现了我的错误,我忘了在activity_eclair中声明ViewStub:

<ViewStub
        android:id="@+id/vsHeader"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inflatedId="@+id/header"
        android:layout="@layout/header" />