2015-12-08 70 views
1

我想使用Chinese blog中的代码在Android ViewPager中显示WebView在ViewPager中显示WebView

public class PagerActivity extends Activity { 

private ViewPager vpArticle; 
private MyPagerAdapter myAdapter; 
private List<View> mListViews; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    setContentView(R.layout.pager); 

    myAdapter = new MyPagerAdapter(); 
    vpArticle = (ViewPager) findViewById(R.id.viewpager); 
    vpArticle.setAdapter(myAdapter); 

    mListViews = new ArrayList<View>(); 
    addView(mListViews, "file:///android_asset/jan.html"); 
    addView(mListViews, "file:///android_asset/feb.html"); 
} 

private void addView(List<View> viewList,String url) 
{ 
    WebView webView=new WebView(this); 
    webView.loadUrl(url); 
    viewList.add(webView); 
} 

private class MyPagerAdapter extends PagerAdapter { 

    @Override 
    public void destroyItem(View arg0, int arg1, Object arg2) { 
     Log.d("k", "destroyItem"); 
     ((ViewPager) arg0).removeView(mListViews.get(arg1)); 
    } 

    @Override 
    public void finishUpdate(View arg0) { 
     Log.d("k", "finishUpdate"); 
    } 

    @Override 
    public int getCount() { 
     Log.d("k", "getCount"); 
     return mListViews.size(); 
    } 

    @Override 
    public Object instantiateItem(View arg0, int arg1) { 
     Log.d("k", "instantiateItem"); 
     ((ViewPager) arg0).addView(mListViews.get(arg1), 0); 
     return mListViews.get(arg1); 
    } 

    @Override 
    public boolean isViewFromObject(View arg0, Object arg1) { 
     Log.d("k", "isViewFromObject"); 
     return arg0 == (arg1); 
    } 

但是,当我尝试运行它时,出现NullPointerException错误。

12-08 19:44:48.093 4968-4968/? E/AndroidRuntime: Caused by: java.lang.NullPointerException 
12-08 19:44:48.093 4968-4968/? E/AndroidRuntime:  at .PagerActivity$MyPagerAdapter.getCount(PagerActivity.java:61) 
12-08 19:44:48.093 4968-4968/? E/AndroidRuntime:  at android.support.v4.view.ViewPager.setAdapter(ViewPager.java:439) 
12-08 19:44:48.093 4968-4968/? E/AndroidRuntime:  at .PagerActivity.onCreate(PagerActivity.java:30) 

线61 return mListViews.size();和线30 vpArticle.setAdapter(myAdapter);

是否有我错过了任何步骤?我是一名Android开发自学者,技能有限。

回答

3

移动

vpArticle.setAdapter(myAdapter); 

mListViews = new ArrayList<View>(); 
addView(mListViews, "file:///android_asset/jan.html"); 
addView(mListViews, "file:///android_asset/feb.html"); 

后,您在return mListViews.size();

+1

多亏了NPE因为mListViews ==null。是工作! – user2872856

+0

@ user2872856酷budy !!!欢迎!!! –