android - 尝试将 OnClickListener 添加到按钮时出现 NullPointerException

标签 android

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

相关文章:

android - 从 JSON 响应填充 Gridview

android - 安全异常 : Permission denial for DEVICE_POWER

android - NPE 在 Android 中动态初始化 TableRows

java - 在 Android 应用程序中通过 Google Plus 进行用户身份验证

android - Glide-4.0.0 缺少占位符,错误,GlideApp 并且不解析其方法占位符,错误

android - 如何以编程方式为 LinearLayout 指定 layout_below?

android - 启用 StrictMode 的 Crashlytics(检测全部)给出 "untagged socket detected"

java - 无法实例化 ViewPagerIndicator CirclePageIndicator

java - 移动Android View并防止onDraw被一遍又一遍地调用

java - 如何在android中执行.sql文件?