Android Util类中的最佳做法

问题描述 投票:0回答:1

创建android util类的最佳实践是什么? 用singelton或其他东西创建静态方法或普通方法会更好吗?这些类应该是可重用的。

单例的常规方法:

public class KeyboardUtils {

    private static final KeyboardUtils instance = new KeyboardUtils();

    private KeyboardUtils() {}

    public static KeyboardUtils getInstance() {
        return instance;
    }

    public void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public void focusEt(final EditText et) {
        et.setOnFocusChangeListener((view, hasFocus) -> {
            if (!hasFocus) {
                hideKeyboard(view);
            }
        });
    }
}

静态方法:

public class KeyboardUtils {

    public static void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public static void focusEt(final EditText et) {
        et.setOnFocusChangeListener((view, hasFocus) -> {
            if (!hasFocus) {
                hideKeyboard(view);
            }
        });
    }
}
java android static singleton
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.