订阅对话框按钮时点击NPE

时间:2017-06-12 10:59:55

标签: android android-dialog rx-java2 butterknife rx-binding

我在我的应用程序中创建了一个自定义对话框,我想添加按钮单击observables,如下所示:

public class BasicDialog extends android.app.Dialog {

    @BindView(R.id.button1)
    TextView button1;
    @BindView(R.id.button2)
    TextView button2;

    public BasicDialog(Context context) {
        super(context);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_basic);

        ...

        ButterKnife.bind(this);
    }

    public Observable<Object> button1Clicks() {
        return RxView.clicks(button1);
    }

    public Observable<Object> button2Clicks() {
        return RxView.clicks(button2);
    }
}

然后我创建了我的对话框并在我的活动中订阅按钮1点击:

@Override
protected void onCreate(Bundle savedInstanceState) {

    ...

    BasicDialog basicDialog = new BasicDialog(this);

    basicDialog.button1Clicks()
            .subscribe(__ -> doStuff());
}

这会导致空指针异常,因为button1在订阅时为空。

我知道可能的解决方法是在对话框中使用PublishSubject而不是尝试直接订阅按钮点击observable,但这似乎是一个非常不优雅的解决方案。

提前感谢任何建议!

1 个答案:

答案 0 :(得分:1)

问题是,您订阅按钮太早


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        ...

        BasicDialog basicDialog = new BasicDialog(this);
        // `basicDialog` hasn't yet been created, it has no view hierarchy inflated yet

        // Force create the dialog
        basicDialog.create();

        // Now you have your dialog created
        basicDialog.button1Clicks()
                .subscribe(__ -> doStuff());
    }