Android:避免选项卡片段中的webview刷新

时间:2013-08-08 09:11:12

标签: android android-webview

我正在创建一个包含2个标签的应用,其中一个标签包含WebView。 问题是每次我在标签之间切换时,WebView都会刷新。

我的结构是:

我创建了操作栏并向标签扩展了片段

我的tab2类代码:

public class CopyOfTab2 extends Fragment implements ActionBar.TabListener{

    private Fragment mFragment;
    private WebView mWebview ;
    private Bundle webViewBundle;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getActivity().setContentView(R.layout.activity_tab2);
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.e("RH", "in OnCreateView");
        View v = inflater.inflate(R.layout.activity_tab2, container, false);
        //ImageView imageView = (ImageView)v.findViewById(R.id.my_image);
        return v;
    }   

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

        mWebview = (WebView)view.findViewById(R.id.GalleryWebView);
        //gallery.setAdapter(adapter);

        mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript

            mWebview.setWebViewClient(new WebViewClient() {
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    Log.e("RH","error in web rh");
                    //Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
                }
            });

            if (webViewBundle == null) {
                Log.e("RH","webViewBundle null");
                mWebview.loadUrl("http://www.google.com");      
            } 
            else {
                Log.e("RH","webViewBundle not null");
                mWebview.restoreState(webViewBundle);               
            }

        super.onViewCreated(view, savedInstanceState);
    }

    public void onTabSelected(Tab tab, FragmentTransaction ft) {

        //switchContent("tab2");

            // TODO Auto-generated method stub
            mFragment = new CopyOfTab2();
            // Attach fragment1.xml layout
            ft.add(android.R.id.content, mFragment);
            ft.attach(mFragment);

    }

    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub
        // Remove fragment1.xml layout
        //ft.remove(mFragment);
        ft.hide(mFragment);
    }

    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub
    }
}

1 个答案:

答案 0 :(得分:0)

我正在使用类似的方法并遇到同样的问题,因为每次选择选项卡时都会创建一个新的片段实例:

mFragment = new CopyOfTab2();

因此一切都会再次执行。