1 package org.robolectric.shadows; 2 3 import android.os.IBinder; 4 import android.os.ResultReceiver; 5 import android.view.View; 6 import android.view.inputmethod.InputMethodManager; 7 import com.google.common.base.Optional; 8 import org.robolectric.annotation.HiddenApi; 9 import org.robolectric.annotation.Implementation; 10 import org.robolectric.annotation.Implements; 11 import org.robolectric.shadow.api.Shadow; 12 13 @Implements(value = InputMethodManager.class, callThroughByDefault = false) 14 public class ShadowInputMethodManager { 15 /** 16 * Handler for receiving soft input visibility changed event. 17 * 18 * Since Android does not have any API for retrieving soft input status, most application 19 * relies on GUI layout changes to detect the soft input change event. Currently, Robolectric are 20 * not able to simulate the GUI change when application changes the soft input through {@code 21 * InputMethodManager}, this handler can be used by application to simulate GUI change in response 22 * of the soft input change. 23 */ 24 public interface SoftInputVisibilityChangeHandler { 25 void handleSoftInputVisibilityChange(boolean softInputVisible); 26 } 27 28 private boolean softInputVisible; 29 private Optional<SoftInputVisibilityChangeHandler> visibilityChangeHandler = Optional.absent(); 30 31 @HiddenApi @Implementation 32 static public InputMethodManager peekInstance() { 33 return Shadow.newInstanceOf(InputMethodManager.class); 34 } 35 36 @Implementation 37 public boolean showSoftInput(View view, int flags) { 38 return showSoftInput(view, flags, null); 39 } 40 41 @Implementation 42 public boolean showSoftInput(View view, int flags, ResultReceiver resultReceiver) { 43 setSoftInputVisibility(true); 44 return true; 45 } 46 47 @Implementation 48 public boolean hideSoftInputFromWindow(IBinder windowToken, int flags) { 49 return hideSoftInputFromWindow(windowToken, flags, null); 50 } 51 52 @Implementation 53 public boolean hideSoftInputFromWindow(IBinder windowToken, int flags, 54 ResultReceiver resultReceiver) { 55 setSoftInputVisibility(false); 56 return true; 57 } 58 59 @Implementation 60 public void toggleSoftInput(int showFlags, int hideFlags) { 61 setSoftInputVisibility(!isSoftInputVisible()); 62 } 63 64 public boolean isSoftInputVisible() { 65 return softInputVisible; 66 } 67 68 public void setSoftInputVisibilityHandler( 69 SoftInputVisibilityChangeHandler visibilityChangeHandler) { 70 this.visibilityChangeHandler = 71 Optional.<SoftInputVisibilityChangeHandler>of(visibilityChangeHandler); 72 } 73 74 private void setSoftInputVisibility(boolean visible) { 75 if (visible == softInputVisible) { 76 return; 77 } 78 softInputVisible = visible; 79 if (visibilityChangeHandler.isPresent()) { 80 visibilityChangeHandler.get().handleSoftInputVisibilityChange(softInputVisible); 81 } 82 } 83 } 84