4

我创建了简单的片段。

片段类

public class MyFragment extends Fragment {
static int count = 0;
static TextView tv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i("TEST", "oncreate");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.frag, container, false);
    tv = (TextView) view.findViewById(R.id.tv);
    return view;
}

public static TextView setMyText(String text) {
    tv.setText(text);
    return tv;
}
}

但问题是 onCreate 片段被调用了两次(当第一次启动活动时)。任何人都知道为什么?事实上,每个生命周期方法都会被调用两次(onAttach、onResume..)。如果有人想知道,我不是在旋转屏幕或任何东西。这是常见的情况还是我在这里做错了什么?

活动课

 public class MainActivity extends FragmentActivity {

private static int COUNT = 0;
private static int COUNT2 = 5;

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

    ViewPager vp = (ViewPager) findViewById(R.id.vp);
    vp.setAdapter(new MyAdapter(getSupportFragmentManager()));
    vp.setOnPageChangeListener(new CustomPageListener());       
}


private static class MyAdapter extends FragmentStatePagerAdapter {

    public MyAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {

    MyFragment mf = new MyFragment();
    return mf;      
    }

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

}

private class CustomPageListener extends ViewPager.SimpleOnPageChangeListener {



    @Override
    public void onPageSelected(int position) {

        MyFragment.setMyText("This is page "+position);

    }

}

}
4

1 回答 1

0

默认情况下FragmentStatePagerAdapter将为 ViewPager 实例化两个页面。onCreate 它被调用了两次,每个片段返回一次 public Fragment getItem(int position)

于 2013-06-18T09:35:38.413 回答