【问题标题】:MapView Fragment displays black (the View is null) when screen powers on again再次开机时,MapView Fragment 显示黑色(View 为空)
【发布时间】:2012-06-16 20:17:06
【问题描述】:

我在 Fragment 中的 MapView 解决方案主要基于 ChristophK、user1414726 和 inazaruk 在此 SO 帖子中提供的示例:mapview-in-a-fragment

当在 Fragment 中调用 onPause() 时,会进行一些清理以避免 IllegalArgumentException。 onPause 和 onStop 中的代码:

if (mapViewContainer != null) {
mapViewContainer.setVisibility(View.GONE);
((ViewGroup) mapViewContainer.getParent()).removeView(mapViewContainer);
mapViewContainer = null;
}

当在滑动到其他 Fragment 时调用 onPause 时效果很好,因为当 MapActivity 再次可见时,onCreateView(..) 在 Fragment 中被覆盖,其中 mapViewContainer 被重新实例化。

但是当我关闭屏幕时;当屏幕重新开机时,onCreateView(..) 不会被覆盖(onPaused 和 onResume 调用工作正常)。这会导致 MapView 显示为黑色,因为在 onPause 中的 removeView 调用中视图为空,直到在一些交互后再次调用 onCreateView(..)。

当屏幕重新开机时,如何强制 onCreateView 覆盖或以某种方式将 MapView 添加回 Fragment?

onCreateView(..) 中的代码:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// This is where you specify you activity class
Intent i = new Intent(getActivity(), MapTabActivity.class);
Window w = mLocalActivityManager.startActivity("tag", i);
mapViewContainer = w.getDecorView();
mapViewContainer.setVisibility(View.VISIBLE);
mapViewContainer.setFocusableInTouchMode(true);
((ViewGroup)
mapViewContainer).setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
return mapViewContainer; }

干杯。

【问题讨论】:

    标签: android google-maps tabs android-fragments android-mapview


    【解决方案1】:

    我可能已经找到了我们问题的答案。我不认为这是一个好的,但它似乎工作..

    如果您在 onStart() 中保存对 mapViewContainer 的父级(我将其设为静态)的引用,您可以在 onResume() 中将 mapViewContainer 添加到父级(如果它尚未包含)。

    这是我所做的:

    private static ViewParent parent;
    @Override
    public void onStart() {
        super.onStart();
    
        parent = mapViewContainer.getParent();      
    
    }
    
    @Override
    public void onResume() {
        super.onResume();
    
    
        if(mapViewContainer != null && parent != null && ((FrameLayout) parent).findViewById(mapViewContainer.getId()) == null) {
            ((FrameLayout) parent).addView(mapViewContainer);
        }
    }
    

    在 onPause() 中我没有设置 mapViewContainer == null,所以我可以重复使用它。

    如果您有任何改进此“解决方案”的建议,非常欢迎!

    希望对你有帮助。

    干杯

    【讨论】:

    • 太棒了!我假设我可以从第一个 onCreateView 调用中获取父级,但关键是从 onStart 中获取它,就像您在该代码中所做的那样。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    相关资源
    最近更新 更多