我在Java类中执行以下操作,而不是在Activity中执行以下操作。尝试将OnClickListener添加到按钮时发生NullPointerException
LinearLayout buttonLayout = (LinearLayout) parentContext.getLayoutInflater().inflate(R.layout.app_dialog, null);
Button btnSignIn = (Button) parentContext.findViewById(R.id.BTN_ID_SIGN_IN);
Button btnCancel = (Button) parentContext.findViewById(R.id.BTN_ID_CANCEL);
btnSignIn.setOnClickListener(new OnClickListener(){
public void onClick(View v) { ... }});
布局的xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/footer" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="horizontal"
android:layout_alignParentBottom="true" style="@android:style/ButtonBar" >
<Button android:id="@+id/BTN_ID_SIGN_IN" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_weight="1"
android:text="@string/em_btn_signin" />
<Button android:id="@+id/BTN_ID_CANCEL" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_weight="1"
android:text="@string/em_btn_cancel" />
</LinearLayout>
最后一行抛出NPE。当我在没有onClickListener的情况下尝试我的代码时,按钮显示完美(尽管当我点击它们时没有任何反应)。为什么它不让我设置任何按钮?
你能发表更多的代码吗?什么是parentContext? – 2012-07-14 01:09:33
parentContext是调用Activity的上下文。我是从一个单独的课程中完成的,这不是一个活动)。 – PlanetaryFortressRush 2012-07-14 01:11:52
为什么你有“空”作为你的膨胀的第二个参数?第二个参数应该是根布局。 – 0gravity 2012-07-14 01:12:35