我在 Java 类中执行以下操作,而不是在 Activity 中执行。
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 的情况下尝试我的代码时,按钮会完美显示(尽管当我点击它们时没有任何反应)。为什么它不允许我对按钮进行任何设置?
最佳答案
试试这个:
Button btnSignIn = (Button) buttonLayout.findViewById(R.id.BTN_ID_SIGN_IN);
Button btnCancel = (Button) buttonLayout.findViewById(R.id.BTN_ID_CANCEL);
btnSignIn.setOnClickListener(new OnClickListener(){
public void onClick(View v) { ... }});
关于android - 尝试将 OnClickListener 添加到按钮时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11480162/