如何使用Viewpager实现ListViews? [英] How do I implement ListViews with Viewpager?

查看:122
本文介绍了如何使用Viewpager实现ListViews?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是android开发的菜鸟,我正试图在viewpager中显示一个listview.但是,当我尝试运行该应用程序时,由于存在nullpointerexception,它在onCreate期间崩溃.这行引起异常:

I'm a noob to android develop and i am trying to show a listview within a viewpager. However, when i try to run the application it crashes during onCreate due to a nullpointerexception. This line is causing the exception:

listView.setAdapter(new UserItemAdapter(MyPagerActivity.this, R.layout.listitem, tweets));

我使用了此处教程,所以我不明白为什么会有这个问题.我是否正确实例化了列表视图?任何帮助,我们将不胜感激.

i used the tutorial here so i don't understand why i am having this issue. Am I instantiating the listview properly? Any help is greatly appreciated.

public class MyPagerActivity extends Activity {

///////////////////////
ArrayList<Tweet> tweets;
ProgressDialog dialog;
Handler handler; 
ImageLoader tango;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mypagermain);

    MyPagerAdapter adapter = new MyPagerAdapter();
    ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
    myPager.setAdapter(adapter);
    myPager.setCurrentItem(0);

    //////////////////////
    tango = new ImageLoader(MyPagerActivity.this); 
    tweets = new ArrayList<Tweet>();

    try {           
        JSONObject jArray = JSONfunctions.getJSONfromURL("http://search.twitter.com/search.json?q=gold%20silver%20news&rpp=15");
        JSONArray parsedTwitter = jArray.getJSONArray("results");       
        if(parsedTwitter.equals("") ){
            Toast.makeText(MyPagerActivity.this, "No twitter news", Toast.LENGTH_LONG).show();
        }else{
            for (int i = 0; i < parsedTwitter.length(); i++) {
            JSONObject parsedspecific = parsedTwitter.getJSONObject(i);             
        if (i == 0){                
            String from_user = parsedspecific.getString("from_user");
            String text = parsedspecific.getString("text"); 
            String profile_image_url = parsedspecific.getString("profile_image_url");  
            Tweet tweet0 = new Tweet(from_user, text, profile_image_url );
            tweets.add(tweet0);                 
            }

              }//<--for close
            }//<--else close

    } catch (Exception e) {
        Log.e("log_tag", "Error parsing data "+ e.toString());
    }

    ListView listView = (ListView) findViewById(R.id.ListViewId);  
    listView.setAdapter(new UserItemAdapter(MyPagerActivity.this, R.layout.listitem, tweets));

}



private class MyPagerAdapter extends PagerAdapter {

    public int getCount() {
        return 5;
    }

    public Object instantiateItem(View collection, int position) {

        LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);


        int resId = 0;
        switch (position) {
        case 0:
            resId = R.layout.news;
            break;
        case 1:
            resId = R.layout.coinshows;
            break;
        case 2:
            resId = R.layout.twitterlist;
            break;
        case 3:
            resId = R.layout.videos;
            break;
    //  case 4:
    //      resId = R.layout.farright;
    //      break;
        }

        View view = inflater.inflate(resId, null);

        ((ViewPager) collection).addView(view, 0);

        return view;
    }



}

XML导致null:

XML causing null:

<?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" >

<ListView
    android:id="@+id/ListViewId"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

</LinearLayout>

MyPagerMain XML:

MyPagerMain XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@+id/tab2"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.support.v4.view.ViewPager
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:id="@+id/myfivepanelpager"
android:background="#234567"/>
</LinearLayout>

根据丹尼斯·德鲁(Dennis Drew)的答案进行编辑(仍然会导致空指针)

EDIT based on Dennis Drew's answer (still causes nullpointer)

private class MyPagerAdapter extends PagerAdapter {

    public int getCount() {
        return 5;
    }

    public Object instantiateItem(View collection, int position) {

        LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);


        int resId = 0;
        switch (position) {
        case 0:
            resId = R.layout.news;
            View view0 = inflater.inflate(resId, null);
            WebView newsfeed = (WebView) findViewById(R.id.webViewnews);
            ((ViewPager) collection).addView(view0, 0);
            return view0;

        case 1:
            resId = R.layout.coinshows;
            View view1 = inflater.inflate(resId, null);
            WebView coinshows = (WebView) findViewById(R.id.webViewcoinshows);
            ((ViewPager) collection).addView(view1, 0);
            return view1;

        case 2:
            resId = R.layout.twitterlist;
            View view2 = inflater.inflate(resId, null);
            LinearLayout layout=(LinearLayout)view2.findViewById(R.id.LLtwitter);
            ListView listView = (ListView) findViewById(R.id.ListViewId);  
            listView.setAdapter(new UserItemAdapter(MyPagerActivity.this, R.layout.listitem, tweets));
            ((ViewPager) collection).addView(view2, 0);
            return view2;
            //break;
        case 3:
            resId = R.layout.videos;
            View view3 = inflater.inflate(resId, null);             
            WebView youtube = (WebView) findViewById(R.id.webViewyoutube);
            ((ViewPager) collection).addView(view3, 0);
            return view3;


        }
        return resId;


    }

推荐答案

正在发生的事情是您的findViewById在ListView上返回null,因为它位于ViewPager内部.当前项目的视图膨胀后,必须在PagerAdapter的InstantiateItem中初始化ListView.在此处检查我对类似问题的答案: ViewPager findViewById

What's happening is your findViewById is returning null on the ListView because it is inside the ViewPager. You must initialize your ListView in your PagerAdapter's instantiateItem after the view for the current item has been inflated. Check my answer to a similar issue here: ViewPager findViewById

通过示例代码进行更新

public Object InstantiateItem(View collection,int position){

public Object instantiateItem(View collection, int position) {

    LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);


    int resId = 0;
    switch (position) {
    case 0:
        resId = R.layout.news;
        View view0 = inflater.inflate(resId, null);
        WebView newsfeed = (WebView) findViewById(R.id.webViewnews);
        ((ViewPager) collection).addView(view0, 0);
        return view0;

    case 1:
        resId = R.layout.coinshows;
        View view1 = inflater.inflate(resId, null);
        WebView coinshows = (WebView) findViewById(R.id.webViewcoinshows);
        ((ViewPager) collection).addView(view1, 0);
        return view1;

    case 2:
        resId = R.layout.twitterlist;
        View view2 = inflater.inflate(resId, null);
        LinearLayout layout=(LinearLayout)view2.findViewById(R.id.LLtwitter);

        //Pay close attention to this modification
        //Rather than this --> ListView listView = (ListView) findViewById(R.id.ListViewId);  

        //Do this
        ListView listView = (ListView)view2.findViewById(R.id.ListViewId);
        listView.setAdapter(new UserItemAdapter(MyPagerActivity.this, R.layout.listitem, tweets));
        ((ViewPager) collection).addView(view2, 0);
        return view2;
        //break;
    case 3:
        resId = R.layout.videos;
        View view3 = inflater.inflate(resId, null);             
        WebView youtube = (WebView) findViewById(R.id.webViewyoutube);
        ((ViewPager) collection).addView(view3, 0);
        return view3;


    }
    return resId;


}

想想您的InstantiateItem方法几乎就像一个sub-onCreate,在某种意义上,您不仅要调用findViewById,还必须在每个单独的寻呼机项目中膨胀的视图上调用findViewById,以执行findViewById(view.findViewById).希望这会有所帮助.

Think of your instantiateItem method almost like a sub-onCreate, in the sense that instead of just calling findViewById, you must call findViewById on the view that's inflated in each individual pager item to do findViewById (view.findViewById). Hope this helps.

这篇关于如何使用Viewpager实现ListViews?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆