如何在碎片中获取根视图?

14

我正在使用这个库在我的应用程序上使用表情符号键盘。 https://github.com/ankushsachdeva/emojicon

说明文档指出活动布局层次结构的最顶层视图必须用于初始化弹出窗口。

我的应用程序是通过片段实现的。

这是我用于测试的代码:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.overview1_layout, container,
            false);

    // Give the topmost view of your activity layout hierarchy. This will be used to measure soft keyboard height
    EmojiconsPopup popup = new EmojiconsPopup(view, getActivity());

    //Will automatically set size according to the soft keyboard size        
    popup.setSizeForSoftKeyboard();

    popup.showAtBottom();


    return view;
}

如果我运行这段代码,我在Logcat中会得到以下错误:

11-02 22:37:16.685: E/AndroidRuntime(30363): java.lang.RuntimeException: Unable to resume activity {com.Testing.full/com.Testing.full.MainActivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?

编辑:我正在使用SherlockFragment


1
getActivity().getWindow().getDecorView().getRootView(); - Pramod Garg
2个回答

6

把视图保存为fragment的实例成员,并在OnViewCreated方法中初始化Emojicons弹出窗口。这可能会解决你的问题。

public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.overview1_layout, container,
        false);

this.view = view

return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

// Give the topmost view of your activity layout hierarchy. This will be used to measure soft keyboard height
EmojiconsPopup popup = new EmojiconsPopup(view, getActivity());




//Will automatically set size according to the soft keyboard size        
popup.setSizeForSoftKeyboard();

popup.showAtBottom();
}

关于问题标题 - 请查看这里


它一直以相同的错误崩溃。我还尝试使用view.getRootView()。 - tobias
你能否尝试在活动内部执行它,看异常是否仍然存在? - Heisenberg
如果我将代码添加到活动的onCreate方法中,它也会崩溃。我做错了什么? - tobias

1
FragmentonStart()或其他回调方法中,在onCreateView之后调用:
emojiconsPopup = new EmojiconsPopup(**getView()**, getActivity());
emojiconsPopup.setSizeForSoftKeyboard();

另一种选择是:

emojiconsPopup = new EmojiconsPopup(  getView().getRootView()  , getActivity());
emojiconsPopup.setSizeForSoftKeyboard();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接