0

我使用DialogFragment包含一个webview。在显示DialogFragment后,当按下后退按钮时,应用程序将返回活动视图。如果按下显示DialogFragment按钮,webview将再次加载init url。但我的要求是,如果第二次打开DialogFragment,我想上次加载的webview显示页面。我怎样才能做到这一点?DialogFragment findFragmentByTag return null

我当前的想法是保持DialogFragment实例,当按下显示按钮,然后检查活动是否已经有DialogFragment。但在我的代码中,findFragmentByTag总是返回null,那有什么问题?或者我应该在DialogFragment中做一些工作?

主要活动代码:

mcWebViewDialog m_webviewDialog = null; 

public void showWebviewDialog() 
{ 

    FragmentManager fragmentManager=getFragmentManager(); 
    FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction(); 
    Fragment prev=fragmentManager.findFragmentByTag("mcWebDialog"); 

    if(prev!=null) 
    { 
     Log.v("seayoung","m_webviewDialog not null"); 
     fragmentTransaction.show(prev); 
    } 
    else 
    { 
     Log.v("seayoung","m_webviewDialog null"); 
     m_webviewDialog=mcWebViewDialog.newInstance(); 
     m_webviewDialog.set_loadurl("file:///android_asset/input.html"); 
     m_webviewDialog.show(fragmentManager,"mcWebDialog"); 
    } 
} 

WebViewDialog代码:

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

     //other code 
     m_webView.loadUrl(m_loadurl); 

     return m_webView; 
    } 

回答

0

当你按下回你的对话片段被破坏并从堆栈中删除,因此你是在执行findFragmentByTag越来越空,以及当用户按下后不会是一个好主意,但作为替代方法,您可以尝试在本地缓存创建的片段,如下所示。

HashMap<String,WeakReference<DialogFragment>> dialogMap = new HashMap<>(); 

// call this before callin `show` 
dialogMap.put(TAG,new WeakReference<>(YOUR_FRAGMENT)); 

和接下来的时间,然后才能执行此

DialogFragment prev=fragmentManager.findFragmentByTag("mcWebDialog"); 
if(prev == null){ 
    prev = dialogMap.get("mcWebDialog").get(); 
} 
if(prev!=null){ 
    Log.v("seayoung","m_webviewDialog not null"); 
    fragmentTransaction.show(prev); 
} 
+0

'分组= dialogMap.get( “mcWebDialog”)获得();'但是如何表现呢? – spartawhy117

+0

最后我更新了我的回答 – Techfist

+0

,我选择隐藏对话框而不是存储它。 – spartawhy117