16

我有 3 个片段 A、B、CI 编写了一段代码来替换它们并维护后台堆栈:

 public void addFragment(Fragment fragmentToAdd, String fragmentTag) {
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        Fragment activeFragment = getActiveFragment();
        FragmentTransaction fragmentTransaction = supportFragmentManager
                .beginTransaction();
        if (null != activeFragment) {
            fragmentTransaction.hide(activeFragment);
        }
        fragmentTransaction.replace(R.id.layout_child_activity, fragmentToAdd,
                fragmentTag);

       if (supportFragmentManager.getBackStackEntryCount() > 1) {
            supportFragmentManager.popBackStack();
        }
        fragmentTransaction.addToBackStack(fragmentTag);
        fragmentTransaction.commit();
    }

在这段代码中

if (supportFragmentManager.getBackStackEntryCount() > 1) {
    supportFragmentManager.popBackStack();
}

如果堆栈长度大于 1,我使用弹出最新片段。现在由于这个原因,当长度大于 1 时,它会一次又一次地调用 onCreate 视图。喜欢 :

  1. 打开 A。
  2. 打开 B。
  3. 打开 C。(在打开 C 的情况下。调用 A 的 onCreateView。)

为什么我会出现这种行为?当我删除该斜体代码时,它不会发生。

4

3 回答 3

12

正如文档所说,行为是正常的,来自后台事务。backstack 从不保存 Fragments,它只是保存事务

在此处输入图像描述

http://developer.android.com/intl/es/guide/components/fragments.html

我不确定我所做的是否是最好的方法,但是当我想清除所有交易时,我会这样做

1)在您的活动中检查后台堆栈中是否有任何事务,并在您的片段中添加一个标志,在您的情况下是 A

       int backStackCount = getSupportFragmentManager().getBackStackEntryCount();

       if(backStackCount > 0) {
           Transactions.MUST_DETACH_FROM_BACKSTACK = true;
           getSupportFragmentManager().popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
       }

2)在您的片段A中,获取标志并删除片段onCreateView并像这样返回null

public class Transactions extends android.support.v4.app.Fragment{

public static boolean MUST_DETACH_FROM_BACKSTACK = false;

public Transactions() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    Log.i("FRAGMENT", "onCreateView "+MUST_DETACH_FROM_BACKSTACK);
    // Inflate the layout for this fragment
    if (MUST_DETACH_FROM_BACKSTACK) {
        MUST_DETACH_FROM_BACKSTACK = false;
        getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
        return null;
    }
    return inflater.inflate(R.layout.fragment_transactions, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);


    Log.i("FRAGMENT", "onViewCreated");
    if(view != null){

        Log.i("FRAGMENT", "ThreadStarted");
        startThread(view);
    }
}

但要小心我得到 onResume() 之后调用

OnCreateView()

即使使用 getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();

因此,如果您有任何 conde onResume 方法,您应该正确处理它

于 2016-02-02T21:14:37.250 回答
0

在此处输入图像描述

记住 a 的生命周期fragment。当我们回到这一点时,它将从oncreateView()永远开始。但是我们仍然可以保存数据,然后我们将在 oncreated 中处理这些数据以填充我们的视图。对你来说,你可以这样做:

主要活动.java

public class MainActivity extends AppCompatActivity implements Fragment2.myListener {
private static final String TAG = "MainActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.e(TAG, "onCreate: ");
    setContentView(R.layout.activity_main);

    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Fragment1 fragment1 = Fragment1.newInstance();
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragmentContainer, fragment1, Fragment1.TAG);
            fragmentTransaction.addToBackStack(Fragment1.TAG);
            fragmentTransaction.commit();
        }
    });

}

@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
    super.onSaveInstanceState(outState, outPersistentState);
    Log.e(TAG, "onSaveInstanceState");
}

@Override
protected void onDestroy() {
    super.onDestroy();
    Log.e(TAG, "onDestroy");
}

@Override
public void bindCount(int newCount) {
    ((Fragment1)getSupportFragmentManager().findFragmentByTag(Fragment1.TAG)).setCount(newCount);
}

}

片段1.java

public class Fragment1 extends Fragment {
public static final String TAG = "fragment1";
private static final String SAVE_COUNT = "save_count";

private int count;

public Fragment1() {
}

public static Fragment1 newInstance() {
    Fragment1 fragment = new Fragment1();
    return fragment;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.e(TAG, "onCreate: ");
    if (savedInstanceState != null) {
        count = savedInstanceState.getInt(SAVE_COUNT);
    }
}

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

    View view =  inflater.inflate(R.layout.fragment_fragment1, container, false);


    Button goToButton = (Button) view.findViewById(R.id.button);
    goToButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Fragment2 fragment2 = Fragment2.newInstance();
            FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragmentContainer, fragment2, Fragment2.TAG);
            fragmentTransaction.addToBackStack(Fragment2.TAG);
            fragmentTransaction.commit();
        }
    });

    return view;
}

public  void setCount(int newCount){
    count = newCount;
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    Log.e(TAG, "onSaveInstanceState: ");
    outState.putInt(SAVE_COUNT, count);
}

}

片段2.java

public class Fragment2 extends Fragment {
public static final String TAG = "fragment2";

public Fragment2() {
    // Required empty public constructor
}

public static Fragment2 newInstance() {
    Fragment2 fragment = new Fragment2();

    return fragment;
}

myListener listener;

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

    View view = inflater.inflate(R.layout.fragment_fragment2, container, false);
    //Here I am just modifying a value that wants to send to fragment1
    listener.bindCount(45);//newCount

    return view;
}

public interface myListener{
    void bindCount(int newCount);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    //initialice listener
    listener = (myListener) getActivity();
}

}

所以...对于我们之间的通信,fragments我们将需要您的容器activity,通过接口。正如我们所看到的,Fragment2 有一个interface实现它的方法,当它被执行时,它会调用一个方法,我们更改存储在 中activity的计数值,因此即使再次执行,我们也可以恢复发生的任何修改。这可以用于许多其他数据,例如等。fragment1onSaveInstanceStateoncreateviewarraylist, string, float, long, object,

对不起我的“英语”!!!!!!

于 2020-04-22T17:49:06.123 回答
0

我通过从我的自定义 BaseFragment (2) 继承 (1) 所有片段解决了这个问题。在这个 BaseFragment 中,我创建了一个变量: public static boolean removal;(3) 并在调用 popBackStackImmediate() 之前将其设置为 true (4),然后将其重置为 false。(5) 在 BaseFragment-childs 我检查变量。(6)

示例代码

活动类

    BaseFragment.removing = true; //(4)
    //pop all fragments
    while(getSupportFragmentManager().getBackStackEntryCount() > 0){
        fragmentManager.popBackStackImmediate();
    }
    BaseFragment.removing = false; //(5)

基本片段 (2)

public class BaseFragment extends Fragment{
   public static boolean removing = false; //(3)
}

片段-孩子

public class fragment extends BaseFragment{ //(1)
  @Override
  public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
      if(!removing){ // (6)
          //your code
      }
  }
}
于 2018-08-24T07:55:21.997 回答