我有一个 FragmentActivity
使用 ViewPager
来服务于几个片段。每一个 ListFragment
具有以下布局:
I have a FragmentActivity
using a ViewPager
to serve several fragments. Each is a ListFragment
with the following layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp">
<ListView android:id="@id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<EditText android:id="@+id/entertext"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
当开始活动,软键盘显示。为了解决这个问题,我做了段内的以下内容:
When starting the activity, the soft keyboard shows. To remedy this, I did the following inside the fragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Save the container view so we can access the window token
viewContainer = container;
//get the input method manager service
imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
. . .
}
@Override
public void onStart() {
super.onStart();
//Hide the soft keyboard
imm.hideSoftInputFromWindow(viewContainer.getWindowToken(), 0);
}
我传入的ViewGroup容器
参数从 onCreateView
另存为的方式来访问窗口令牌的主要活动。这将运行没有错误,但键盘没有得到从调用隐藏到 hideSoftInputFromWindow
在 ONSTART
。
I save the incoming ViewGroup container
parameter from onCreateView
as a way to access the window token for the main activity. This runs without error, but the keyboard doesn't get hidden from the call to hideSoftInputFromWindow
in onStart
.
本来,我试着用充气布局而不是容器
,即:
Originally, I tried using the inflated layout instead of container
, i.e:
imm.hideSoftInputFromWindow(myInflatedLayout.getWindowToken(), 0);
但这扔了 NullPointerException异常
,presumably因为片段本身并不是一个活动,没有一个独特的窗口令牌?
but this threw a NullPointerException
, presumably because the fragment itself isn't an activity and doesn't have a unique window token?
有没有办法隐藏软键盘从片段中,或者我应该在 FragmentActivity
创建一个方法,并从片段中调用它?
Is there a way to hide the soft keyboard from within a fragment, or should I create a method in the FragmentActivity
and call it from within the fragment?
只要你的片段创建一个视图中,可以从该视图使用的IBinder(窗口标记)的在的已连接。例如,你可以在你的碎片覆盖onActivityCreated:
As long as your Fragment creates a View, you can use the IBinder (window token) from that view after it has been attached. For example, you can override onActivityCreated in your Fragment:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
}