为什么片段的onCreateView,的onCreate,onActivityCreated被称为 [英] Why does the fragment's onCreateView, onCreate, onActivityCreated are called

查看:106
本文介绍了为什么片段的onCreateView,的onCreate,onActivityCreated被称为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,与碎片和ViewPager处理。我有一个ViewPager三个片段。当你在它们之间进行切换时,它总是会导致其他两个片段来调用它们的onCreateView方法。如何做它只有一次,创建FragmentActivity只有当??? 我读过一些问题,并试图解决方案,但碎片还是有相同的行为。

I have an app, that deals with fragments and ViewPager. I have three fragments in a ViewPager. When you switch between them, it always causes the other two fragments to call their's onCreateView methods. How to do it only once, only when FragmentActivity is created??? I've read some questions and tried the solutions, but the fragments still have the same behavior.

ListFragment的onCreate调用两次
<一href="http://stackoverflow.com/questions/7223166/oncreate-and-oncreateview-invokes-a-lot-more-than-required-fragments">onCreate()和onCreateView()调用了大量超过所需的(片段)

下面是一些code,如果它可以帮助你,伙计们:

Here is some code, if it helps you, guys:

MainActivity:

MainActivity:

public class StartingActivity extends FragmentActivity implements View.OnClickListener {
ViewPager viewPager;
    CirclePageIndicator pageIndicator;

    Button discount;
    Button qrCode;
    Button pay;
    TabHost tabHost;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.starting_layout);
        viewPager = (ViewPager) findViewById(R.id.pager);

        if (savedInstanceState == null) {

            Fragment firstPage = Fragment.instantiate(this, FindTovarFragment.class.getName());
            Fragment secondPage = Fragment.instantiate(this, MainWindowActivity.class.getName());
            Fragment thirdPage = Fragment.instantiate(this, MapActivity.class.getName());

            if ((firstPage != null && !firstPage.isDetached())|| (secondPage != null && !secondPage.isDetached()) || (thirdPage != null && !thirdPage.isDetached())) {

            List<Fragment> viewPagerFragments = new ArrayList<Fragment>();
            viewPagerFragments.add(firstPage);
            viewPagerFragments.add(secondPage);
            viewPagerFragments.add(thirdPage);


            PageAdapter pageAdapter = new PageAdapter(getSupportFragmentManager(), viewPagerFragments);

            viewPager.setAdapter(pageAdapter);

            pageIndicator = (CirclePageIndicator) findViewById(R.id.circle);
            pageIndicator.setViewPager(viewPager);
            pageIndicator.setCurrentItem(pageAdapter.getCount() - 2);
            }
        }

}

MapActivity:

MapActivity:

public class MapActivity extends Fragment implements OnMyLocationListener {

    //Тэг для логов
    private static final String TAG = "MapActivity";
    List<Address> addressList;
    private static final String STRING_LOCATION = "";

    ArrayList<TorgCentr> randomTorgCentr;
    ArrayList<String> torgCentrNames;

    Context context;
    AutoCompleteTextView searchTorgCentr;
    OverlayManager overlayManager;
    MapController mapController;
    TextView textView;
    double longitude;
    double latitude;
    double itemLongitude;
    double itemLatitude;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "MapActivity onCreateView");


        View view = (LinearLayout) inflater.inflate(R.layout.map_layout, container, false);
        final MapView mapView = (MapView) view.findViewById(R.id.map);
        textView = (TextView) view.findViewById(R.id.searchlocation);
        searchTorgCentr = (AutoCompleteTextView) view.findViewById(R.id.autoCompleteTextView);

        mapView.showBuiltInScreenButtons(true);
        mapController = mapView.getMapController();
        context = getActivity();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "MapActivity onCreate");

    }

    public void onActivityCreated(Bundle savedInstanceState) {
        Log.d(TAG, "MapActivity onActivityCreated");
        context = getActivity();

        SetRightMapDisplayAddress rightMapDisplayAddress = new SetRightMapDisplayAddress();
        rightMapDisplayAddress.execute(STRING_LOCATION);

        DownloadSuperMarketsArray superMarketsArray = new DownloadSuperMarketsArray();
        superMarketsArray.execute();

        overlayManager = mapController.getOverlayManager();
        overlayManager.getMyLocation().setEnabled(false);

        super.onActivityCreated(savedInstanceState);
    }

第二个片段:

Second Fragment:

public class MainWindowActivity extends Fragment {

    private static final String TAG = "MainWindowActivity";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "MainWindowActivity onCreateView");
        View view = (RelativeLayout) inflater.inflate(R.layout.main_window_layout, container, false);
        if (container == null) {
            return null;
        }
        return view;
    }
}

和第三个:

public class FindTovarFragment extends Fragment {

    private static final String TAG= "FindTovarFragment";

    Context context;
    ArrayList<Category> categories;
    Spinner categoryContainer;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "FindTovarFragment onCreateView");

        View view = (LinearLayout) inflater.inflate(R.layout.find_tovar_main_layout, container, false);
        categoryContainer = (Spinner) view.findViewById(R.id.category);

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(TAG, "FindTovarFragment onActivityCreated");
        DownloadCategory downloadCategory = new DownloadCategory();
        downloadCategory.execute();
    }

日志为MapActivity:

Logs for MapActivity:

06-20 11:06:37.709: DEBUG/MapActivity(1290): MapActivity onCreate
06-20 11:06:37.709: DEBUG/MapActivity(1290): MapActivity onCreateView
06-20 11:06:38.509: DEBUG/MapActivity(1290): MapActivity onActivityCreated

然后一遍又一遍:

Then again and again:

06-20 11:07:53.239: DEBUG/MapActivity(1290): MapActivity onCreate
06-20 11:07:53.239: DEBUG/MapActivity(1290): MapActivity onCreateView
06-20 11:07:53.429: DEBUG/MapActivity(1290): MapActivity onActivityCreated
06-20 11:08:23.029: DEBUG/MapActivity(1290): MapActivity onCreate
06-20 11:08:23.039: DEBUG/MapActivity(1290): MapActivity onCreateView
06-20 11:08:23.269: DEBUG/MapActivity(1290): MapActivity onActivityCreated

非常感谢你提前。

Thank you very much in advance.

推荐答案

我会改变你的架构为这一个在Android开发者文档:

I would change your architecture for this one on the android developer documentation:

<一个href="http://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html">http://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html

但我会改变一些事情...

but I would change some things...

1,我想改变这个方法:

1-I would change this method:

/**
     * The Fragment's UI is just a simple text view showing its
     * instance number.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
        View tv = v.findViewById(R.id.text);
        ((TextView)tv).setText("Fragment #" + mNum);
        return v;
    }

这样的事情,我们决定哪些片段您填充取决于viewPager的位置:

For something like this where we decide which fragment you populate depending the position of the viewPager:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);

SupportFragmentManager ft = getChildFragmentManager().beginTransaction();

String tag = "";
Fragment fragment = null;

  switch (mNum) {
  case 0:
    fragment = new MyFragmentZero();
    tag = FragmentTags.TAG_0;
    break;
  case 1:
    fragment = new MyFragmentOne();
    tag = FragmentTags.TAG_3;
    break;
  case 2:
    fragment = new MyFragmentTwo();
    tag = FragmentTags.TAG_2;
    break;
  default:
    break;
  }

/*OPTIONAL We can pass arguments to the fragments
Bundle args = new Bundle();
args.putInt(Arguments.ARG_POSITION, mNum);
fragment.setArguments(args);*/

//Place the fragment in the container
ft.replace(R.id.fragment_container fragment, tag);
ft.commit();

//You need a base layout for all fragment and use nested fragments later or you can define the layout for each position(mNum) inside the switch.
return inflater.inflate(R.layout.fragment_layout_default_for_all_views, container,
    false);
}

这样你将有一个良好的体系结构,一旦它正在像这样应该就可以了。

Like this you will have a good architecture and once it is working like this should be fine.

反正你必须知道viewPager如何工作的填充在不同位置的片段。

Anyway you must know how the viewPager works populating the fragment in the different positions.

当你开始对位0,然后在位置0的片段和1位中的一个被创建。

When you start on the position 0, then the fragment on the position 0 and the one of the position 1 are created.

然后,当你刷到2位的片段创建的,所以你现在有不同的位置创建的三个片段的位置1(0,1,2..assuming你只有3对viewPager页)

Then when you swipe to the position 1 the fragment on the 2 position is created, so you have now the three fragments created on the different positions (0,1,2..assuming you have only 3 pages on the viewPager).

我们轻扫到位置2,最后一个,并且在第一位置的片段(0)获得破坏,所以我们现在上的位置2和3的片段。

We swipe to the position 2, the last one, and the fragment on the first position (0) get destroy, so we have now the fragments on the positions 2 and 3.

我希望它帮助,让我知道,如果你有任何问题。干杯

I hope it helped and let me know if you have any problem. Cheers

这篇关于为什么片段的onCreateView,的onCreate,onActivityCreated被称为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆