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

时间:2015-02-18 00:00:50

标签: java android fragment fragmentpageradapter

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

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()));

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

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

page = getArguments() != null ? getArguments().getInt("position") : 0;