当我在标签之间切换时,我在列表视图中失去了变量

时间:2016-04-14 09:05:54

标签: android listview variables tabs android-viewpager

就像我说的那样:例如我在Tab1中,在里面我有一个自定义列表视图,其中连续存在一个EditText对象。

因此,如果我放5,例如,它会改变,但如果我转到tab3然后我返回到tab1,EditText中的值将返回到0.

这是我的活动,带标签:

enter image description here

这是ViewPagerHolder.java

package com.faddex.ristorante;
class ViewPagerAdapter extends FragmentStatePagerAdapter {

CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created


// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
    super(fm);

    this.Titles = mTitles;
    this.NumbOfTabs = mNumbOfTabsumb;

}

//This method return the fragment for the every position in the View Pager
@Override
public Fragment getItem(int position) {

    if(position == 0) // if the position is 0 we are returning the First tab
    {
        Tab1 tab1 = new Tab1();
        return tab1;
    }
    if(position == 1) // if the position is 0 we are returning the First tab
    {
        Tab2 tab2 = new Tab2();
        return tab2;
    }
    if(position == 2)
    {
        Tab3 tab3 = new Tab3();
        return tab3;
    }
    if(position == 3)
    {
        Tab4 tab4 = new Tab4();
        return tab4;
    }
    if(position == 4)
    {
        Tab5 tab5 = new Tab5();
        return tab5;
    }
    else 
    {
        Tab6 tab6 = new Tab6();
        return tab6;
    } 
}

// This method return the titles for the Tabs in the Tab Strip

@Override
public CharSequence getPageTitle(int position) {
    return Titles[position];
}

// This method return the Number of tabs for the tabs Strip

@Override
public int getCount() {
    return NumbOfTabs;
}

}

如何防止重置?

3 个答案:

答案 0 :(得分:3)

设置第一个和小的方法

 viewPager.setOffscreenPageLimit(5);

第二种方法是 保存Fragment的所有数据

@Override
    public void setUserVisibleHint(boolean visible)
    {
        super.setUserVisibleHint(visible);

            if (!visible)
            {
                // save all data some where
            }

    }

修改

对于您,您可以在addTextChangedLinsterner

上按EditText将数据存储在模型中

答案 1 :(得分:0)

在每个片段中尝试使用此代码以保留其状态onCreate方法:

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

答案 2 :(得分:0)

您应该将edittext值保存在某种模型中,以便正确恢复状态。

然后在此页面的RecyclerView适配器中设置此值。