有没有办法创建条件监听器

时间:2015-02-01 14:18:18

标签: android listener

有没有办法创建一个在特定条件下激活事件的侦听器(布尔值)?

我尝试阅读有关使用界面创建自定义侦听器但我不认为它是我的问题的答案。

现在在我的应用程序中我在任何地方都写了一个if语句,所以如果我能为它创建一个监听器,那就容易多了。

set_A==B_Listener(????? {//listener takes place if a==b
        @Override
        public boolean event(View v, MotionEvent e)
        {
             //do something
        }
    });

1 个答案:

答案 0 :(得分:0)

为您的语句创建一个类变量,而不是将OnChangeListener附加到您的Activity的onCreate方法中的语句

public class DummyActivity extends Activity {


interface OnStateChangeListener{

    public void onAttach(Activity activity);
    public void onStateChange(boolean state);
}

private boolean state;
private OnStateChangeListener listener;
private YourClass stateChangedCallback;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    listener = new OnStateChangeListener() {

        private Activity currentActivity;

        @Override
        public void onAttach(Activity activity) {
            currentActivity = activity;
        }

        @Override
        public void onStateChange(boolean state) {
            if (((DummyActivity) this.currentActivity).state != state) {
                stateChangedCallback.doSomething();
                ((DummyActivity) this.currentActivity).state = state;
            }
        }
    };
}



private void yourFunction() {
    boolean state = true;
    listener.onStateChange(state);

}

}