我正在使用V4兼容性JAR。我有一個顯示某些樂隊信息的ViewPager。當我創建PagerAdapter時,我將它傳遞給Band對象的ArrayList。ViewPager無法正確顯示查看
在模擬器中,它總是顯示首先顯示ArrayList信息中的第二個band。當我翻到最後一個視圖時,視圖始終沒有數據。當我來回翻轉時,數據會變得非常麻煩。
BandsActivity
private ViewPager mBandsPager;
private BandsPagerAdapter mBandsPagerAdapter;
private static final String TAG = "Paging";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.awesomepager);
// Build a couple bands;
ArrayList<Band> bands = new ArrayList<Band>();
bands.add(new Band(1, "Led Zeppelin"));
bands.add(new Band(37, "Brand New"));
bands.add(new Band(49, "Jay-Z"));
mBandsPagerAdapter = new BandsPagerAdapter(this, bands);
mBandsPager = (ViewPager) findViewById(R.id.awesomepager);
mBandsPager.setAdapter(mBandsPagerAdapter);
}
BandsPagerAdapter
private Context mCtx;
private ArrayList<Band> mBands;
public BandsPagerAdapter(Context ctx, ArrayList<Band> bands) {
mCtx = ctx;
mBands = bands;
}
@Override
public int getCount() {
return mBands.size();
}
@Override
public Object instantiateItem(View collection, int position) {
// Inflate and create the view
LayoutInflater layoutInflater = (LayoutInflater)mCtx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.featured_bands_layout, null);
// Build UI
TextView name = (TextView)collection.findViewById(R.id.featured_band_name);
// Populate UI with band data
Band band = mBands.get(position);
if(name != null) {
name.setText("Name: " + band.getName() + ", Pos: " + position);
}
// Add View to the ViewPager collection
((ViewPager)collection).addView(view,0);
return view;
}
@Override
public void destroyItem(View collection, int position, Object view) {
((ViewGroup) collection).removeView((View)view);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view==((View)object);
}
@Override
public void finishUpdate(View arg0) {}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View arg0) {}
有什麼建議?我看到提到實現ViewPager.SimpleOnPageChangeListener,但沒有看到它如何正確使用。
這與回答沒有任何關係,但將「collection.findViewById」更改爲「view.findViewById」,則更合適。 –
當您旋轉屏幕時,您的活動將被重新創建,因此上下文將被更改;如此一來,您的pageadaptor將保持不再存在的上下文,並導致內存泄漏! – Raunak
原來是正確的答案!我需要使用我剛膨脹的視圖對象。 TextView name =(TextView)view.findViewById(R.id.featured_band_name); –