WebView有时不会在Fragment中重新加载

时间:2017-02-16 13:29:07

标签: android android-fragments webview tabbed

我是初学者。我正在使用android studio中的标准示例,并使用3个滚动选项卡创建Tabbed Activity。在选项卡textview和webview中。 Textview工作得很好。在WebView内容中有时(10-15中有1个)没有加载到我的设备上(Android 4.4 KitKat) - WebView显示为空白,但如果我滚动或点击屏幕,则显示WebView中的内容。 Adnroid Emulator(Nexus One Api 23,Android 6.0)都运行良好。如何解决?

视频:https://www.youtube.com/watch?v=oQWTszMoNZc(23秒和65秒的错误)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="0dp"
    android:paddingLeft="0dp"
    android:paddingRight="0dp"
    android:paddingTop="0dp"
    tools:context="appname.MyClass$PlaceholderFragment">

    <TextView
        android:text="Section"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView5"
        android:paddingLeft="10dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/webView"
        android:layout_below="@+id/textView5">
    </WebView>
</RelativeLayout>

代码

import ...

public class MyClass extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;
    private AdView mAdView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_diet);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        this.setTitle("My title");

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_show_diet, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";
        public String jsonstr = "NOT";
        public String consultJson = "NOT";
        public Context context;
        ProgressDialog dialog;

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_show_diet, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.textView5);
            String url = "file:///android_asset/herba1.html";
            context = getContext();
            dialog = ProgressDialog.show(getActivity(), "", "Loading...", true);

            //get sec num
            int section = getArguments().getInt(ARG_SECTION_NUMBER);
            textView.setText("Section= "+String.valueOf(section));
            url = "file:///android_asset/herba"+section+".html";

            WebView webView = (WebView) rootView.findViewById(R.id.webView);
            WebSettings webSettings = webView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setLoadWithOverviewMode(true);
            webSettings.setAllowFileAccess(true);
            webView.setWebViewClient(new Client());
            webView.setWebChromeClient(new ChromeClient());
            if (Build.VERSION.SDK_INT >= 19) {
                webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            }
            else if(Build.VERSION.SDK_INT >=11 && Build.VERSION.SDK_INT < 19) {
                webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            }
            webView.addJavascriptInterface(new JavaScriptInterface(), "android");
            webView.loadUrl(url);

            Log.d("my_tag", "Load="+url+" frag="+section);

            return rootView;
        }

        class JavaScriptInterface {
            @JavascriptInterface
            public void openBrowser(String url) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(browserIntent);
            }
        }

        public class ChromeClient extends WebChromeClient {
        }

        public class Client extends WebViewClient {

            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error){
                //view.loadUrl("file:///android_asset/eror.html");
            }

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // If url contains
                if (url.contains("mailto:") || url.contains("tel:")) {
                    //Open links in new browser
                    view.getContext().startActivity(
                            new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    return true;
                }else {
                    // Stay within this webview and load url
                    view.loadUrl(url);
                    return true;
                }
            }
            //Show loader on url load
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                dialog.show();
            }
            public void onPageFinished(WebView view, String url) {
                try {
                    dialog.dismiss();
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            }
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            Log.d("My tag getItem", String.valueOf((position + 1)));
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {

            Log.d("My tag getPageTitle", String.valueOf((position)));

            switch (position) {
                case 0:
                    return "SECTION 1";
                case 1:
                    return "SECTION 2";
                case 2:
                    return "SECTION 3";
            }
            return null;
        }
    }
}

0 个答案:

没有答案