如何在片段中打开键盘

时间:2015-07-10 12:36:28

标签: android android-fragments keyboard

片段启动时如何打开键盘?我已经尝试过这段代码:

@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;
}

但它不起作用。我必须在启动时打开键盘。

4 个答案:

答案 0 :(得分: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);
            }
        });

答案 1 :(得分:2)

显示键盘用途:

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);

答案 2 :(得分:0)

遇到同样的问题,请尝试使用 view.postDelayed(new Runnable() { @Override public void run() { InputMethodManager keyboard = (InputMethodManager) mAppContext .getSystemService(Context.INPUT_METHOD_SERVICE); keyboard.showSoftInput(view, 0); } }, 100);

{
    "category1": [
        {
            "text": "Question text",
            "answers": ["value1", "value2", "value3"]
        },
        {
            "text": "Question text",
            "answers": ["value1", "value2", "value3"]
        },
        {
            "text": "Question text",
            "answers": ["value1", "value2", "value3"]
        }
    ], 
    "category2": [
        {
            "text": "Question text",
            "answers": ["value1", "value2", "value3"]
        },
        {
            "text": "Question text",
            "answers": ["value1", "value2", "value3"]
        },
        {
            "text": "Question text",
            "answers": ["value1", "value2", "value3"]
        }
    ]
}

答案 3 :(得分:0)

在xml中使用requestFocus标记,以便在启动时在片段中打开键盘。 像..

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

    <requestFocus />
</EditText>