2015-06-18 34 views
4

我使用xamarin + mvvmcross創建了Android應用程序。我的MvxFragment中有一個MvxAutoCompleteTextView。在寫入MvxAutoCompleteTextView並單擊其他控件後,我想要隱藏虛擬鍵盤。我用這個代碼關閉/隱藏MvxFragment中的Android軟鍵盤

public class MyFragment : MvxFragment 
{ 
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    { 

     base.OnCreateView(inflater, container, savedInstanceState); 
     var view = this.BindingInflate(Resource.Layout.frMy, null); 
     var autoComplete = view.FindViewById<MvxAutoCompleteTextView>(Resource.Id.acMy); 
     InputMethodManager inputManager = (InputMethodManager)inflater.Context.GetSystemService(Context.InputMethodService); 
     inputManager.HideSoftInputFromWindow(autoComplete.WindowToken, HideSoftInputFlags.None); 
     return view; 
    } 
} 

但這不起作用。我如何隱藏鍵盤?

回答

2

試試這個:

InputMethodManager imm = (InputMethodManager)GetSystemService(Context.InputMethodService); 
imm.HideSoftInputFromWindow(autoComplete.WindowToken, 0); 

0 in HideSoftInputFromWindow is const Android.Views.InputMethods.HideSoftInputFlags.None因此您可以使用等效語法:

InputMethodManager imm = (InputMethodManager)GetSystemService(Context.InputMethodService); 
imm.HideSoftInputFromWindow(autoComplete.WindowToken, Android.Views.InputMethods.HideSoftInputFlags.None); 
1

嘗試我的功能:

public static void Close_AndroidKeyboard(Activity context){ 
    InputMethodManager inputManager = (InputMethodManager) context.getSystemService(
      Context.INPUT_METHOD_SERVICE); 
    inputManager.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(), 
      InputMethodManager.HIDE_NOT_ALWAYS); 
} 

很抱歉,但我與Android的工作室工作,告訴我,如果我幫助你,良好的編程!

+0

謝謝,但它對我不起作用。 – FetFrumos

5

您可以隱藏軟鍵盤,將焦點放在不屬於「鍵盤啓動器」控件的位置,例如,自動完成控件的父容器。

parentContainer = FindViewById<LinearLayout>(Resource.Id.parentContainer); 
parentContainer.RequestFocus(); 

Let's說你的父容器是一個LinearLayout中,你應該允許它獲得關注與這2個屬性:

<LinearLayout 
    android:id="@+id/parentContainer" 
    android:focusable="true" 
    android:focusableInTouchMode="true"> 
3

我從這裏Java中的答案:https://stackoverflow.com/a/28939113/4664754

這裏是C#版本(測試工作):

public override bool DispatchTouchEvent(MotionEvent ev) 
{ 
    if (ev.Action == MotionEventActions.Down) 
    { 
     View v = CurrentFocus; 
     if (v.GetType() == typeof(EditText)) 
     { 
      Rect outRect = new Rect(); 
      v.GetGlobalVisibleRect(outRect); 
      if (!outRect.Contains((int)ev.RawX, (int)ev.RawY)) 
      { 
       v.ClearFocus(); 
       InputMethodManager imm = (InputMethodManager)this.GetSystemService(Context.InputMethodService); 
       imm.HideSoftInputFromWindow(v.WindowToken, 0); 
      } 
     } 
    } 
    return base.DispatchTouchEvent(ev); 
} 

這段代碼會隱藏鍵盤,如果你的軟點擊任何不是EditText的東西。 您只需將其粘貼到您的活動課程中(例如您的登錄活動)