浅谈Android app开发中Fragment的Transaction操作

2019-12-10 18:57:12于海丽

浅谈Android app开发中Fragment的Transaction操作

同时Fragment的View也会被detach。在重新调用attach()后,onCreateView()-onResume()周期也会被再次执行。

浅谈Android app开发中Fragment的Transaction操作

remove()
其实看完上面的分析,remove()方法基本也就明白了。相对应add()方法执行onAttach()-onResume()的生命周期,remove()就是完成剩下的onPause()-onDetach()周期。

浅谈Android app开发中Fragment的Transaction操作

 

错误

曾经在FragmentTransaction编写时遇到过以下错误:

复制代码
The method replace(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, MyFragment)
Fragment newfragment =new MyFragment();
fragmentTransaction.replace(R.layout.activity_main,newfragment ).commit();

 

提示错误:The method replace(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, MyFragment)

原因找了好久!一直以为子类对象不能赋值给父类引用。这不科学啊!

代码时这样的:

package com.example.testforfragment;

import android.os.Bundle;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.support.v4.app.Fragment.*;
import android.view.Menu;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  FragmentManager fragmentManager = getFragmentManager();
  FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
  Fragment newfragment =new MyFragment();
  fragmentTransaction.replace(R.layout.activity_main,newfragment ).commit();
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

}