我正在使用FragmentStatePagerAdapter
在Fragmets
中列出我的ViewPager
。每个片段只包含一个WebView
。一切正常,我只想使用PagerAdapter
的预加载机制,它预先加载1 Fragment
。这是我Fragment
的简化代码:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.ecard_fragment, container, false);
webview = (WebView) view;
webview.loadDataWithBaseURL("", HTML, "text/html", "utf-8", "");
Toast.makeText(getActivity(), "fragment: " + NAME, Toast.LENGTH_SHORT).show();
return view;
}
我确定,下一个Fragment
已预生成,因为Toast
已提前显示。但WebView
稍后会加载 - 就在关注Fragment
之后。如何强制WebView
加载?
答案 0 :(得分:2)
在OnCreate()方法中创建您的webview,然后在OnCreateView()方法中对该webview进行充气。
稍后加载WebView因为onCreateView() - 只有在片段需要将UI加载到用户时才调用方法。
另一方面,OnCreate()在OnCreateView()之前被调用,并且可以实例化片段的基本元素
答案 1 :(得分:0)
我已经编写了简单的演示项目,对我而言,它可以很好地生成邻居视图。这是我的代码:
public class DrawActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle arg0) {
setContentView(R.layout.pager);
((ViewPager) findViewById(R.id.pager)).setAdapter(new ScreenSlidePagerAdapter(getSupportFragmentManager()));
super.onCreate(arg0);
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return new WebViewFragment(position);
}
@Override
public int getCount() {
return 3;
}
}
@SuppressLint("ValidFragment")
private class WebViewFragment extends Fragment {
private WebView mWebView;
private int pos;
public WebViewFragment(int pos) {
this.pos = pos;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mWebView = new WebView(getApplicationContext());
mWebView.loadDataWithBaseURL("", "<h1> ----------------TEST----------------- " + pos + "</h1>", "text/html", "utf-8", "");
Toast.makeText(getActivity(), "fragment: " + this.toString(), Toast.LENGTH_SHORT).show();
return mWebView;
}
}
}
和xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
结果:
答案 2 :(得分:0)
我遇到了同样的问题并通过禁用WebView的硬件加速来修复它:
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
通过WebViews in ViewPager are not loaded/rendered until page is shown