我正在使用片段寻呼机适配器实例化我的片段类.我能够这样做但我的问题是我的getItem()方法被调用两次,这进一步产生了问题.你解释我为什么会发生这种情况.
package com.creatiosoft.rssfeed.adaptor;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;
import com.creatiosoft.rssfeed.utils.RssItem;
import com.viewpagerindicator.IconPagerAdapter;
public class NewsFeedsAdapter extends FragmentPagerAdapter implements
IconPagerAdapter {
int[] icon = null;
String[] content = null;
String[] URLs = null;
Context cont;
public NewsFeedsAdapter(FragmentManager fm, Context context) {
super(fm);
Log.i("jk", "constructor");
this.cont = context;
RssItem newsFeedAppliaction = (RssItem) cont;
/*
* Retrieving the values of the Icons and contents from the application
* class in utils package
*/
icon = newsFeedAppliaction.getICONS();
content = newsFeedAppliaction.getCONTENT();
URLs = newsFeedAppliaction.getURL();
}
/** instantiate a new fragment class */
@Override
public Fragment getItem(int position) {
Log.i("yt", "hello" + position);
return TestFragment.newInstance(position % content.length, cont);
}
@Override
public CharSequence getPageTitle(int position) {
return content[position % content.length].toUpperCase();
}
public int getIconResId(int index) {
return icon[index];
}
/** return the no of views on the basis of array items */
@Override
public int getCount() {
Log.i("hi", "length" + content.length);
return content.length;
}
}
Run Code Online (Sandbox Code Playgroud)
我用这段代码调用Adapter:
NewsFeedsAdapter adapter = new NewsFeedsAdapter(
getSupportFragmentManager(), getApplicationContext());
/**
* get the id of the view pager declared in the xml resource and set the
* adaptor on the view pager
*/
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
//pager.setCurrentItem(0);
/**
* Tab page indicator class is used to indicate the tabs and is accessed
* from the library class
*/
TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(pager);
Run Code Online (Sandbox Code Playgroud)
在 getItem 方法中,您创建片段的新实例。这很糟糕。它让你处于现在的境地。您正在做的是创建一个新的异常项目,该项目将按照您指定的方式生存。但是,当邪恶的 Android 系统决定需要再次与您的 Fragment 通信并向您的适配器请求它时,您就是在告诉它“不。我不想!” 而是给它一个与其旧片段完全相同的新片段。
为了解决这个问题,您需要提前膨胀所有片段,然后返回正确的片段。或者如果你愿意,就不要这样做。但请保留您创建的实例的记录,以便您可以返回已创建的片段。
我不知道为什么它被调用两次 - 我没有搜索 v4 的源代码,但这样做可能是为了确保该项目被实际检索或系统进入需要引用前一个项目的状态。
总之,保留创建的实例 -特别是对于像片段、视图和活动这样重的对象。
class Adapter extends MyWhateverAdapter {
Fragment[] myLovelyFragments;
public Adapter() {
// Instantiate your fragments and place them into myLovelyFragments
}
public int getFragmentCount() {
return myLovelyFragments.length;
}
public Fragment getItem(int position) {
return myLovelyFragments[position];
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5249 次 |
| 最近记录: |