ArrayList显示即使添加元素后其大小也为0

时间:2018-06-20 13:59:48

标签: android arraylist

我有一个ArrayList来存储片段实例。名为“ listofFragInstances”的ArrayList是全局的。我在setUpViewPager()方法中向此ArrayList添加了值。 但是,在setUpViewPager()方法之外的另一种方法中使用它时,在使用调试器时它的大小显示为零,而在setUpViewPager()方法中它的大小是预期的。有什么问题吗?

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.audit_form_activity);   

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        tabLayout = (TabLayout) findViewById(R.id.tabLayout);

        button = (Button) findViewById(R.id.button);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);

        setupViewPager(viewPager);


        viewPager.setOffscreenPageLimit(no_of_categories);


        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        tabLayout.setupWithViewPager(viewPager);


    }


    private void setupViewPager(ViewPager viewPager) {

        //       Outside Loop
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

//        Get the JSON Data from DataSource


        try {
            JSONObject pageObj = new JSONObject(page);
            JSONArray auditQuestionsArray = pageObj.getJSONArray("AuditQuestions");
            int auditQuestionsArrayLength = auditQuestionsArray.length();
            no_of_categories = auditQuestionsArrayLength;


//        Outer-Loop Through the CategoryNames to Create Fragments for each CategoryName.

            for (int i = 0; i < no_of_categories; i++) {
                JSONObject auditQuestionsArrayObject = auditQuestionsArray.getJSONObject(i);
                category = auditQuestionsArrayObject.getString("categoryName");


                Tab1 myFrag = Tab1.newInstance(category);
                listOfFragInstances.add(myFrag);

                adapter.addFrag(myFrag, category);

            }
            viewPager.setAdapter(adapter);


        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

public void activity_saveAll()
{
    for (int i=0; i<listOfFragInstances.size(); i++)
    {
        listOfFragInstances.get(i).saveAnswers();
    }
}

请帮助!

1 个答案:

答案 0 :(得分:0)

您面临的问题是ViewPager处理Fragments的生命周期,这意味着您存储在ArrayList中的实例可能与ViewPager使用的实例不同。

建议不要保留Fragment的实例,并让ViewPager进行工作。老实说,我从来没有能够忍受这个。为了解决您的问题,您需要扩展FragmentManager并在ViewPager内部对其进行更改时替换ArrayList中的实例。

这是我用的。

相关代码为public Object instantiateItem(ViewGroup container, int position),当实例化新的Fragment时,它将替换ArrayList中的Fragment。这不是我的创作,我是从SO的另一个问题中得到的,但不记得是哪个问题。

要获取正确的当前片段实例,请使用public Fragment getCurrentIntance(int position)

这很明显,但以防万一,不要在此类之外保留对Fragments的引用,因为您不知道它们是否是最新的。

public class MySimplePagerAdapter extends FragmentStatePagerAdapter {

    protected final List<Fragment> fragmentList = new ArrayList<>();
    protected final List<String> fragmentTitleList = new ArrayList<>();
    protected final HashMap<Integer,Fragment> currentInstances = new HashMap<>();
    protected FragmentManager fm;

    public MySimplePagerAdapter(FragmentManager manager) {
        super(manager);
        this.fm = manager;
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);

    }

    @Override
    public int getCount() {
        return fragmentList.size();
    }

    //Method to add Tab fragment and Tab name
    public void addFragment(Fragment fragment, String title) {
        fragmentList.add(fragment);
        fragmentTitleList.add(title);
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return fragmentTitleList.get(position);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
        currentInstances.put(position, createdFragment);
        // save the appropriate reference depending on position
        return createdFragment;
    }

    public Fragment getCurrentIntance(int position){
        return currentInstances.get(position);
    }
}