我在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