将位置作为参数传递给FragmentPagerAdapter中的Fragment

问题描述 投票:0回答:2

getItem()的位置并不总是正确的!有时它将显示0、1、2、3、4,然后如果我返回,它将显示不同的位置(4、2、3、1,0)。如果需要将位置传递到arraylist / treemap中,使用“位置”的正确方法是什么?

02-18 20:07:22.453  11479-11479/com.app E/aaa﹕ position created:0
02-18 20:07:22.453  11479-11479/com.app E/aaa﹕ position created:1
02-18 20:07:29.053  11479-11479/com.app E/aaa﹕ position created:2
02-18 20:07:35.503  11479-11479/com.app E/aaa﹕ position created:0

行:

 return SingleCard.newInstance(get_all_cards_as_objects().get(position));

需要正确的位置,而不是将其渲染到内存中!我需要片段内的数据以实际页面位置更改。它将基于实际页面位置知道要从地图获取的数据。

final ViewPager pager = (ViewPager) findViewById(R.id.pager);
        this.parent_nested_fragment_activity = this;

        pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()){
            private final int PARENT_COUNT = get_all_cards_as_objects().size();

            @Override
            public Object instantiateItem(ViewGroup container, final int position) {
                Object obj = super.instantiateItem(container, position);
                pager.setObjectForPosition(obj, position);
                return obj;
            }

            @Override
            public Fragment getItem(int position) {
            Toast.makeText(CardDealer.this,"Selected page position: " + position, Toast.LENGTH_SHORT).show();
            Log.e("aaa", "position created:" + position);
                    return SingleCard.newInstance(get_all_cards_as_objects().get(position));
            }

我有一个像他这样的问题,但是这个答案没有帮助:FragmentPagerAdapter getItem wrong position

我也不确定如何在我的片段中实现此答案:getItem() calling multiple time in FragmentPagerAdapter

像这样:Weird dissappearing Fragments with FragmentPagerAdapter

基本上我已经调查过:

pager.getCurrentItem();

如何使用getItem()将其传递到已创建的片段中]

 return SingleCard.newInstance(get_all_cards_as_objects().get(pager.getCurrentItem()));
java android fragment fragmentpageradapter
2个回答
1
投票

确定,我创建的实际片段出现了问题。我在SingleCard片段内部使用了静态int。将其更改为非静态int可解决问题!

   //problem:
     private static int page;
   //solution:
     private int page;

public class SingleCard extends Fragment {
    public static SingleCard newInstance ( int sent_in_position ) {
        SingleCard fragmentFirst = new SingleCard ();
        Bundle args = new Bundle();
        args.putInt("position", sent_in_position);
        fragmentFirst . setArguments(args);
        return fragmentFirst;
    }

@Override
public void onCreate (Bundle savedInstanceState ) {
    super.onCreate(savedInstanceState);
    page = getArguments().getInt("position", 0);
}

0
投票

另外检查getArguments()是否为null,因为如果为null则会返回错误

page = getArguments() != null ? getArguments().getInt("position") : 0;
© www.soinside.com 2019 - 2024. All rights reserved.