android – 在Fragment上的ViewPager中的片段不会在方向更改时重新加载

android – 在Fragment上的ViewPager中的片段不会在方向更改时重新加载,第1张

概述我正在开发一个使用ActionBarSherlock和ViewPagerIndicator的 Android应用程序.主要活动是SherlockFragmentActivity,用户通过 *** 作栏上的选项卡在片段之间导航.所有选项卡都是SherlockListFragments,大多数只包含ListView.但是,一个片段(HeadlinesFragment)包含ViewPager,CirclePag 我正在开发一个使用ActionbarSherlock和VIEwPagerIndicator的 Android应用程序.主要活动是SherlockFragmentActivity,用户通过 *** 作栏上的选项卡在片段之间导航.所有选项卡都是SherlockListFragments,大多数只包含ListVIEw.但是,一个片段(headlinesFragment)包含VIEwPager,CirclePageIndicator和平板电脑的ListVIEw,以及手机上的ListVIEw. VIEwPager有一个FragmentStatePagerAdapter,它返回项目的SherlockFragment.

问题是,在方向更改(或任何配置更改确实)时,VIEwPager中的子片段不会被重新加载,并且CirclePagerIndicator不会显示任何指示符,就好像VIEwPager是空的一样.但是,ListVIEw确实可以正确重新加载.在片段的初始加载时,VIEwPager可以正常工作,但不能在方向更改后工作.

MainActivity.java

public class MainActivity extends SherlockFragmentActivity {    // =============== Variable Declaration ================    private HashMap<Integer,String> tabData;    private HashMap<Integer,String> tabExtra;    private Fragment currentFragment = null;    private Fragment savedFragment = null;    public Actionbar mActionbar;    public MenuItem mRefresh;    public static int mCurrentPos;    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        HashMap<String,Object> savedData = (HashMap<String,Object>) getLastCustomNonConfigurationInstance();        if (savedData != null) {            tabData = (HashMap<Integer,String>) savedData.get("tabData");            tabExtra = (HashMap<Integer,String>) savedData.get("tabExtra");            savedFragment = (Fragment) savedData.get("currentFragment");            mCurrentPos = ((Integer) savedData.get("pos")).intValue();        } else {            tabData = (HashMap<Integer,String>) getIntent().getExtras().getSerializable("tabData");            tabExtra = (HashMap<Integer,String>) getIntent().getExtras().getSerializable("tabExtra");            mCurrentPos = 0;        }        mActionbar = getSupportActionbar();        Const.Istablet = Utils.istablet(MainActivity.this);        //if (!Const.Istablet) setRequestedOrIEntation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);        TypedArray tabs = getResources().obtainTypedArray(R.array.Tabbars);        Tab tab;        for (int i = 0; i < tabs.length(); i++) {            String tabInfo[] = getResources().getStringArray(tabs.getResourceID(i,0));            tab = mActionbar.newTab().setText(tabInfo[1]);            if (tabInfo[0].equalsIgnoreCase("customizednewsPage")) {                tab.setTabListener(new MainTabListener<headlinesFragment>(MainActivity.this,i,headlinesFragment.class));            }            mActionbar.addTab(tab);        }        tabs.recycle();        mActionbar.selectTab(mActionbar.getTabAt(mCurrentPos));        mActionbar.setNavigationMode(Actionbar.NAVIGATION_MODE_TABS);        //set navbar for ICS+ devices        mActionbar.setBackgroundDrawable(getResources().getDrawable(R.drawable.navbar));    }    @Suppresslint("HandlerLeak")    private Handler mHandler = new Handler() {        @OverrIDe        public voID handleMessage(Message message) {            Bundle bundle = message.getData();            if (bundle.getInt("result") == Activity.RESulT_OK && bundle.getString("data") != null) {                tabData.put(Integer.valueOf(bundle.getInt("tabPos")),bundle.getString("data"));                DataType type = DataType.values()[bundle.getInt("type")];                switch (type) {                    case headlines:                        ((headlinesFragment) currentFragment).setData(bundle.getString("data"));                        break;                }                tabData.put(Integer.valueOf(bundle.getInt("tabPos")),bundle.getString("data"));                setRefreshActionbuttonState(false);            }        }    };    public Handler getHandler() {        return mHandler;    }    @OverrIDe    public Object onRetainCustomNonConfigurationInstance() {        final HashMap<String,Object> savedData = new HashMap<String,Object>();        savedData.put("currentFragment",currentFragment);        savedData.put("tabData",tabData);        savedData.put("tabExtra",tabExtra);        savedData.put("pos",Integer.valueOf(mCurrentPos));        return savedData;    }    private class MainTabListener<T extends Fragment> implements TabListener {        private Fragment mFragment;        private final SherlockFragmentActivity mActivity;        private final int mPos;        private final Class<T> mClass;        /** Constructor used each time a new tab is created. */        public MainTabListener(SherlockFragmentActivity activity,int pos,Class<T> clz) {            mActivity = activity;            mPos = pos;            mClass = clz;        }        @OverrIDe        public voID onTabSelected(Tab tab,FragmentTransaction ignoredFt) {            FragmentManager fragMgr = ((FragmentActivity) mActivity).getSupportFragmentManager();            FragmentTransaction ft = fragMgr.beginTransaction();            // Check if the fragment is already initialized            if (mFragment == null) {                // If not,instantiate and add it to the activity                mFragment = Fragment.instantiate(mActivity,mClass.getname());                Bundle args = new Bundle();                args.putString("data",tabData.get(mPos));                args.putInt("pos",mPos);                mFragment.setArguments(args);                ft.add(androID.R.ID.content,mFragment);            } else {                ft.attach(mFragment);            }            currentFragment = mFragment;            mCurrentPos = mPos;            mRefresh = null;            ft.commit();        }        @OverrIDe        public voID onTabUnselected(Tab tab,FragmentTransaction ignoredFt) {            FragmentManager fragMgr = ((FragmentActivity) mActivity).getSupportFragmentManager();            FragmentTransaction ft = fragMgr.beginTransaction();            fragMgr.popBackStack(null,FragmentManager.POP_BACK_STACK_INCLUSIVE);            // Check if the fragment is already initialized            if (mFragment == null) {                mFragment = SherlockFragment.instantiate(mActivity,mClass.getname());                ft.add(androID.R.ID.content,mFragment);            } else {                ft.detach(mFragment);            }            currentFragment = null;            ft.commit();        }        @OverrIDe        public voID onTabReselected(Tab tab,FragmentTransaction ignoredFt) {            onTabUnselected(tab,ignoredFt);            onTabSelected(tab,ignoredFt);        }    }}

headlinesFragment.java

public class headlinesFragment extends SherlockListFragment implements SearchVIEw.OnqueryTextListener,SearchVIEw.SearchVIEwChangeMode,OnItemClickListener {    private static final String LOG_TAG = "headlines Fragment";    private JsONArray mheadlines = new JsONArray();    private JsONArray mheadlinestop = new JsONArray();    private SearchVIEw mSearchVIEw;    private MenuItem mSearchItem;    private VIEwPager mPager;    private CirclePageIndicator mIndicator;    private static int mPos;    private int mrotatorImageWIDth;    private static headlinesFragment instance;    private Tracker tracker;    private Timer refreshTimer;    private int refreshTime = 0;;    @OverrIDe    public voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setHasOptionsMenu(true);        instance = this;    }    @OverrIDe    public VIEw onCreateVIEw(LayoutInflater inflater,VIEwGroup container,Bundle savedInstanceState) {        mPos = getArguments().getInt("pos");        TypedArray tabs = getResources().obtainTypedArray(R.array.Tabbars);        String tabInfo[] = getResources().getStringArray(tabs.getResourceID(mPos,0));        mrotatorImageWIDth = Integer.valueOf(tabInfo[7]).intValue();        refreshTime = Integer.valueOf(tabInfo[4]).intValue();        tabs.recycle();        try {            mheadlines = new JsONArray(getArguments().getString("data"));        } catch (NotFoundException e) {            Log.e(LOG_TAG,"Error loading data",e);        } catch (JsONException e) {            Log.e(LOG_TAG,e);        }        return inflater.inflate(R.layout.activity_headlines,container,false);    }    @SuppressWarnings("deprecation")    @OverrIDe    public voID onVIEwCreated(VIEw vIEw,Bundle savedInstanceState) {        super.onVIEwCreated(vIEw,savedInstanceState);        //if (Const.Istablet) {        if (((SIDHelpApplication) getActivity().getApplicationContext()).istablet()) {            try {                mheadlinestop = new JsONArray();                JsONArray temp = new JsONArray();                for (int i = 0; i < mheadlines.length(); i++) {                    if (i < 5) {                        mheadlinestop.put(mheadlines.get(i));                    } else {                        temp.put(mheadlines.get(i));                    }                }                mheadlines = temp;            } catch (JsONException e) {                Log.e(LOG_TAG,"Error splitting off top 5",e);            }            mPager = (VIEwPager) getActivity().findVIEwByID(R.ID.rotator);            mPager.setoffscreenPagelimit(4);            mPager.setAdapter(new rotatorAdapter(this,getActivity(),mheadlinestop,mrotatorImageWIDth,mPos));            if (getResources().getConfiguration().orIEntation == Configuration.ORIENTATION_PORTRAIT) {                mPager.getLayoutParams().height = (int) Math.floor((((float) getResources().getInteger(R.integer.NewsImageHeight) / (float) getResources().getInteger(R.integer.NewsImageWIDth)) *  (float) getActivity().getwindowManager().getDefaultdisplay().getWIDth()));            }            mIndicator = (CirclePageIndicator) getActivity().findVIEwByID(R.ID.indicator);            mIndicator.setVIEwPager(mPager);        }        setlistadapter(new headlinesAdapter(getSherlockActivity(),mheadlines));        getListVIEw().setonItemClickListener(this);        getListVIEw().setEmptyVIEw(getActivity().findVIEwByID(androID.R.ID.empty));        setautoRefresh();    }    public voID setData(String data) {        setData(data,false);    }    public voID setData(String data,boolean search) {        try {            mheadlines = new JsONArray(data);            if (((SIDHelpApplication) getActivity().getApplicationContext()).istablet() && !search) {                mheadlinestop = new JsONArray();                try {                    JsONArray temp = new JsONArray();                    for (int i = 0; i < mheadlines.length(); i++) {                        if (i < 5) {                            mheadlinestop.put(mheadlines.get(i));                        } else {                            temp.put(mheadlines.get(i));                        }                    }                    mheadlines = temp;                } catch (JsONException e) {                    Log.e(LOG_TAG,e);                }                ((rotatorAdapter) mPager.getAdapter()).setData(mheadlinestop);                mPager.setVisibility(VIEw.VISIBLE);                mIndicator.setVisibility(VIEw.VISIBLE);            } else {                getActivity().findVIEwByID(androID.R.ID.empty).setVisibility(VIEw.GONE);            }            if (search && mPager != null) {                mPager.setVisibility(VIEw.GONE);                mIndicator.setVisibility(VIEw.GONE);            }            ((headlinesAdapter) getlistadapter()).setData(mheadlines);            setautoRefresh();        } catch (JsONException e) {            Log.e(LOG_TAG,"Setting Data",e);        }    }    public static headlinesFragment getInstance() {        return instance;    }}

activity_headlines.xml

<?xml version="1.0" enCoding="utf-8"?><relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"    androID:ID="@+ID/llMainheadline"    androID:layout_wIDth="match_parent"    androID:layout_height="match_parent"    androID:focusable="false"    androID:focusableIntouchMode="true"    androID:background="@drawable/bg_img" >    <androID.support.v4.vIEw.VIEwPager        androID:ID="@+ID/rotator"        androID:layout_wIDth="match_parent"        androID:layout_height="@dimen/headlines_rotator_height"        androID:layout_alignParenttop="true"        androID:background="@androID:color/black" />    <com.vIEwpagerindicator.CirclePageIndicator        androID:ID="@+ID/indicator"        androID:layout_wIDth="match_parent"        androID:layout_height="wrap_content"        androID:layout_below="@ID/rotator"        androID:background="@androID:color/black"        androID:padding="10dp" />    <ListVIEw        androID:ID="@androID:ID/List"        androID:layout_wIDth="match_parent"        androID:layout_height="match_parent"        androID:layout_alignParentBottom="true"        androID:layout_below="@ID/indicator"        androID:cachecolorHint="#00000000"        androID:ListSelector="@color/tableCellSelection" />    <TextVIEw        androID:ID="@androID:ID/empty"        androID:layout_wIDth="wrap_content"        androID:layout_height="wrap_content"        androID:layout_centerInParent="true"        androID:text="@string/noresults"        androID:textSize="@dimen/noresult_text_size"        androID:textStyle="bold"        androID:visibility="gone" /></relativeLayout>

rotatorAdapter.java

public class rotatorAdapter extends FragmentStatePagerAdapter {    private static final String LOG_TAG = "rotator Adapter";    private Context mContext;    private JsONArray mData;    private int mImageWIDth;    private int mPos;    public rotatorAdapter(SherlockListFragment fragment,Context context,JsONArray data,int imageWIDth,int pos) {        super(fragment.getChildFragmentManager());        mContext = context;        mData = data;        mImageWIDth = imageWIDth;        mPos = pos;    }    @OverrIDe    public int getCount() {        return mData.length();    }    @OverrIDe    public Fragment getItem(int pos) {        Fragment fragment = null;        Bundle args = new Bundle();        try {            JsONObject hdata = mData.getJsONObject(pos);            args.putString("Title",hdata.getString(mContext.getResources().getString(R.string.tag_Title)));            args.putString("category",hdata.getString(mContext.getResources().getString(R.string.tag_category)));            args.putString("time",hdata.getString(mContext.getResources().getString(R.string.tag_time)));            args.putString("newsID",hdata.getString(mContext.getResources().getString(R.string.tag_newsID)));            args.putString("photoURL",hdata.getString(mContext.getResources().getString(R.string.tag_photoURL)));            args.putInt("imageWIDth",mImageWIDth);            args.putInt("pos",mPos);            fragment = Fragment.instantiate(mContext,rotatorFragment.class.getname(),args);        } catch (JsONException e) {            Log.e(LOG_TAG,"Error getting data",e);        }        return fragment;    }    public voID setData(JsONArray data) {        mData = data;        notifyDataSetChanged();    }}

rotatorFragment.java

public class rotatorFragment extends SherlockFragment implements OnClickListener {    private static final String LOG_TAG = "rotator Fragment";    private String mNewsID;    private int mPos;    private ImageLoader imageLoader = ImageLoader.getInstance();    @OverrIDe    public VIEw onCreateVIEw(LayoutInflater inflater,Bundle savedInstanceState) {        VIEw vIEw = inflater.inflate(R.layout.activity_headlines_top_row,false);        // Set the image        ImageVIEw image = (ImageVIEw) vIEw.findVIEwByID(R.ID.imgArticle);        String photoURL = getArguments().getString("photoURL").replaceAll(" ","%20");        imageLoader.displayImage(photoURL,image);        // Set Title,category,and time        TextVIEw headlineTitle = (TextVIEw) vIEw.findVIEwByID(R.ID.txtTitle);        TextVIEw headlinecategory = (TextVIEw) vIEw.findVIEwByID(R.ID.txtcategory);        headlineTitle.setText(getArguments().getString("Title"));        headlinecategory.setText(String.format("%s - %s",getArguments().getString("category"),getArguments().getString("time")));        // Set article ID for onclick Listener        mNewsID = getArguments().getString("newsID");        mPos = getArguments().getInt("pos");        vIEw.setonClickListener(this);        return vIEw;    }    @OverrIDe    public voID onClick(VIEw v) {        // Load article data        Log.i(LOG_TAG,"Loading Article");        Intent dataIntent = new Intent(getActivity(),DataLoader.class);        Messenger dataMessenger = new Messenger(headlinesFragment.mHandler);        dataIntent.putExtra("MESSENGER",dataMessenger);        dataIntent.putExtra("tabPos",mPos);        dataIntent.putExtra("type",DataType.headlinesArticle.ordinal());        String params[] = new String[] {mNewsID};        dataIntent.putExtra("params",params);        getActivity().startService(dataIntent);    }    @OverrIDe    public voID onSaveInstanceState (Bundle outState) {        // Don't save the fragment state    }}
解决方法 我想出了这个问题.问题是当配置发生变化时,AndroID会破坏并重新创建活动,但碎片没有被破坏.它们被添加回管理器,因为代码也被重新创建.因此,在创建新Fragment时未重新创建的VIEwPager未正确引用它.对此的修复是在onTabSelected函数中我检查了管理器中已经存在的Fragment,并且只是使用它而不是重新创建它.我还必须为每个创建的片段添加标签,以便找到我正在寻找的片段.

if (mCurrentTag != null && mCurrentTag.equalsIgnoreCase(mTag) && fragMgr.findFragmentByTag(mCurrentTag) != null) {    mFragment = fragMgr.findFragmentByTag(mCurrentTag);}
总结

以上是内存溢出为你收集整理的android – 在Fragment上的ViewPager中的片段不会在方向更改时重新加载全部内容,希望文章能够帮你解决android – 在Fragment上的ViewPager中的片段不会在方向更改时重新加载所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1125093.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-30
下一篇 2022-05-30

发表评论

登录后才能评论

评论列表(0条)

保存