多点触控监听器,例如Google的“启用开发人员选项和调试”功能

时间:2018-04-20 16:32:28

标签: android

我有一个像这样的SettingsFragment:

public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener 

我得到一个这样的按钮:

Preference button_about = findPreference("button_about");
button_about.setOnPreferenceClickListener(new 
Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // do something
            return true;
        }
    });

我想检测用户是否以快速方式连续多次选中button_about。 Google还使用此功能通过tabbing the "Build number" button 7 times consecutively将手机切换到开发者模式。我想在我的应用程序中实现相同的功能。我该怎么做?

1 个答案:

答案 0 :(得分:1)

使用计数器跟踪点击次数,并使用Handler重置计数器以防止经过一段时间。

示例:

private static final int MAX_DELAY = 2000;
private static final int MIN_TAPS = 5;
private int mCounter = 0;
private Handler mHandler;

private void setOnClickListener() {
    Preference button_about = findPreference("button_about");
    button_about.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {

            mCounter++;

            //if the user did not tap the button within MAX_DELAY, the counter resets
            if (mHandler == null) {
                mHandler = new Handler();
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mCounter = 0;
                    }
                }, MAX_DELAY);
            }

            if (mCounter >= MIN_TAPS) {
                // user tapped MIN_TAPS times consecutively
                // do something...
            }

            return true;
        }
    });
}