2

我在我的应用程序中创建了一个自定义对话框,我想像这样添加按钮点击 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在对话框中使用 a 而不是尝试直接订阅按钮 click observable,但这似乎是一个非常不雅的解决方案。

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

4

1 回答 1

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());
    }

于 2017-06-12T12:29:07.313 回答