2015-07-10 88 views
0

如何在片段啓動時打開鍵盤?我已經試過這個代碼:如何在片段中打開鍵盤

@Override 
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
    view =inflater.inflate(R.layout.mylayout,container,false); 
    TextView TVLarghezza = (TextView) view.findViewById(R.id.larghezza); 
    TVLarghezza.requestFocus(); 
    InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); 
    imgr.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); 
    return view; 
} 

但它不起作用。我必須在啓動時打開鍵盤。

回答

2

也許問題是,在onCreateView,視圖尚未在屏幕上。

嘗試這種情況:

final TextView TVLarghezza = (TextView) view.findViewById(R.id.larghezza); 
TVLarghezza.post(new Runnable() { 
     @Override 
     public void run() { 
      TVLarghezza.requestFocus(); 
      InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); 
      imgr.showSoftInput(TVLarghezza, InputMethodManager.SHOW_IMPLICIT); 
      } 
     }); 
0

對於顯示出鍵盤使用:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0); 

用於隱藏鍵盤使用:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
imm.hideSoftInputFromWindow(view.getWindowToken(),0); 

修訂
對於片段:

imgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY); 
+0

我已經已經嘗試過這種方法,但他們只在活動上工作,而不是在片段 – Damien

+0

@Damien,我已經更新了答案 – Alexander

0

有同樣的問題,嘗試在啓動時使用postDelayed

view.postDelayed(new Runnable() { 
     @Override 
     public void run() { 
      InputMethodManager keyboard = (InputMethodManager) mAppContext 
        .getSystemService(Context.INPUT_METHOD_SERVICE); 
      keyboard.showSoftInput(view, 0); 
     } 
    }, 100); 
0

使用requestFocus的標籤以XML爲開放式鍵盤在片段.. 如..

<EditText 
    android:id="@+id/edPswrd" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:ems="10" 
    android:inputType="textPassword" > 

    <requestFocus /> 
</EditText>