Created
January 16, 2015 04:36
-
-
Save lenguyenthanh/446f7cce9929e04b51a1 to your computer and use it in GitHub Desktop.
Util file to hide keyboard with current EditText
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.annotation.SuppressLint; | |
import android.content.Context; | |
import android.os.Bundle; | |
import android.os.Handler; | |
import android.os.IBinder; | |
import android.os.ResultReceiver; | |
import android.os.SystemClock; | |
import android.view.MotionEvent; | |
import android.view.inputmethod.InputMethodManager; | |
import android.widget.EditText; | |
/** | |
* @author lenguyenthanh on 7/17/14. | |
*/ | |
public final class EditTextUtil { | |
private EditTextUtil() { | |
} | |
@SuppressLint("Recycle") | |
public static void startEditWithKeyboard(final EditText aText) { | |
Handler handler = new Handler(); | |
handler.postDelayed(() -> { | |
aText.requestFocus(); | |
aText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0, 0, 0)); | |
aText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0, 0, 0)); | |
aText.setSelection(aText.length()); | |
}, 60); | |
} | |
public static abstract class KeyboardListener extends ResultReceiver { | |
public KeyboardListener() { | |
super(new Handler()); | |
} | |
@Override | |
protected final void onReceiveResult(int resultCode, Bundle resultData) { | |
if (resultCode == InputMethodManager.RESULT_HIDDEN) { | |
onHidden(); | |
} | |
} | |
protected void onHidden() { | |
} | |
} | |
public static void hideKeyboard(Context aContext, final EditText aText) { | |
hideKeyboard(aContext, aText, null); | |
} | |
public static void hideKeyboard(Context aContext, final EditText aText, KeyboardListener listener) { | |
hideKeyboard(aContext, aText.getWindowToken(), listener); | |
} | |
public static void hideKeyboard(Context aContext, final IBinder aWindowToken, KeyboardListener listener){ | |
InputMethodManager imm = (InputMethodManager) aContext.getSystemService(Context.INPUT_METHOD_SERVICE); | |
imm.hideSoftInputFromWindow(aWindowToken, 0, listener); | |
} | |
public static void toggleKeyboard(Context aContext, final EditText aText) { | |
InputMethodManager input = (InputMethodManager) aContext.getSystemService(Context.INPUT_METHOD_SERVICE); | |
input.toggleSoftInputFromWindow(aText.getWindowToken(), 0, 0); | |
} | |
public static boolean isEmpty(final EditText aEditText){ | |
return Strings.isBlank(aEditText.getText()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment