android 调用OnPreferenceClickListener中的函数

vmdwslir  于 2023-02-20  发布在  Android
关注(0)|答案(1)|浏览(129)

我正在尝试调用OnPreferenceClickListener中的函数,而该函数是在另一个类中定义的。由于我还没有设法初始化OnPreferenceClickListener中的接口。我给出了下面的示例代码:

public void onCreatePreferences(Bundle bundle, String s) {

    ListPreference preference = findPreference(getString(R.string.settings_ble_choose_device_key));

    preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(@NonNull Preference preference) {

            callFunctionInMainActivity();

            return false;
        }
    });
}

如何调用一个在另一个类中实现的函数?
非常感谢
雷内

mrfwxfqh

mrfwxfqh1#

您可以为此实现一个Intent,即从OnPreferenceClickListener类发送广播,并实现在另一个类中接收的广播,以侦听此Intent并调用所需的方法。以下是一个示例:

public void onCreatePreferences(Bundle bundle, String s) {

    ListPreference preference = findPreference(getString(R.string.settings_ble_choose_device_key));

    preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(@NonNull Preference preference) {

                        sendBroadcast(new Intent(Constants.ACTION_STOP_MAIN_SERVICE));

            return true;
        }
    });
}

在你的另一堂课上:

private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        String action= intent.getAction();
        if(action.equalsIgnoreCase(ConstantesIdentifiant.ACTION_STOP_MAIN_SERVICE)){
            finishAffinity();
        }
    }
};

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        registerReceiver(broadcastReceiver, new IntentFilter(ConstantesIdentifiant.ACTION_STOP_MAIN_SERVICE));
}

@Override
protected void onDestroy() {
    unbindService(mConnection);
    unregisterReceiver(broadcastReceiver);
    super.onDestroy();
}

相关问题