1

我想在viewpager中使用listview。嘗試調用虛擬方法void android.widget.AdapterView.setAdapter(android.widget.Adapter)

這裏是我的代碼:

我的片段:CampaignsFragment

@Override 
public void onViewCreated(View view, Bundle savedInstanceState) { 
    // BEGIN_INCLUDE (setup_viewpager) 
    // Get the ViewPager and set it's PagerAdapter so that it can display items 
    mViewPager = (ViewPager) view.findViewById(R.id.viewpager_campaigns); 
    mViewPager.setAdapter(new CampaignsAdapter(getFragmentManager())); 
    // END_INCLUDE (setup_viewpager) 


    // BEGIN_INCLUDE (setup_slidingtablayout) 
    // Give the SlidingTabLayout the ViewPager, this must be done AFTER the ViewPager has had 
    // it's PagerAdapter set. 
    mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs_campaigns); 
    mSlidingTabLayout.setViewPager(mViewPager); 
    // END_INCLUDE (setup_slidingtablayout) 
} 

我的適配器:CampaignsAdapter

public class CampaignsAdapter extends FragmentPagerAdapter { 

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

    /** 
    * @return the number of pages to display 
    */ 
    @Override 
    public int getCount() { 
     return 2; 
    } 

    @Override 
    public Fragment getItem(int position) { 
     String[] campaigns_type = {"active", "previous"}; 

     //Log.w(String.valueOf(position), String.valueOf(position)); 
     return CampaignsListFragment.newInstance(campaigns_type[position]); 
    } 
} 

這是我的一個片段:CampaignsListFragment

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

    if (getArguments() != null) { 
     mCampaignType = getArguments().getString(ARG_CAMPAIGN_TYPE); 
    } 

    // TODO: Change Adapter to display your content 
    mAdapter = new ArrayAdapter<DummyContent.DummyItem>(getActivity(), 
      android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS); 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.fragment_campaigns_list, container, false); 

    // Set the adapter 
    mListView = (AbsListView) view.findViewById(android.R.id.list); 
    ((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter); 

    // Set OnItemClickListener so we can be notified on item clicks 
    mListView.setOnItemClickListener(this); 

    return view; 
} 

但是我面臨的問題:

顯示java.lang.NullPointerException:嘗試在com.safaroff.bakcellroaming上的空對象引用 調用虛擬方法「無效android.widget.AdapterView.setAdapter(android.widget.Adapter)」 .CampaignsListFragment.onCreateView(CampaignsListFragment.java:83)

enter image description here

enter image description here

有什麼問題嗎?

回答

2

我解決了我的問題。問題是這裏:

mListView = (AbsListView) view.findViewById(android.R.id.list); 

我已經改變了這一點。

mListView = (AbsListView) view.findViewById(R.id.listview_campaigns); 
相關問題