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

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,单击我的 Activity ,如下所示:
@Override
protected void onCreate(Bundle savedInstanceState) {

    ...

    BasicDialog basicDialog = new BasicDialog(this);

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

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

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

在此先感谢您的任何建议!

最佳答案

问题是,您订购按钮单击的时间过早。
@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()); }

09-05 02:09