无法删除片段

时间:2013-12-28 19:46:20

标签: android android-fragments

我在这里要做的是在传入的“show”广播上添加一个片段(这很好),然后在传入的“隐藏”广播中删除它 - 这不起作用,片段不被隐藏(但是广播被发送)。调用fragmentTransaction.add()fragmentTransaction.remove(),但只有fragmentTransaction.add()可以工作。在调用fragmentTransaction.remove()之后,片段仍然存在。

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Get extra data included in the Intent
        String message = intent.getStringExtra("message");
        Log.v("receiver", "Got message");

  if(intent.getStringExtra("message").equals("show")) {

      Log.v("fragment", "I'm trying show!");

      fragmentManager = getFragmentManager();
      fragmentTransaction = fragmentManager.beginTransaction();
      Remote fragment2 = new Remote();
      fragmentTransaction.add(R.id.fragment_container, fragment2, "RecordingRemote");
      fragmentTransaction.commit();
      fragmentManager.executePendingTransactions();


        } else if (intent.getStringExtra("message").equals("hide")) {

      Log.v("fragment", "I'm trying to hide!");

      fragmentManager = getFragmentManager();
      fragmentTransaction = fragmentManager.beginTransaction();
      Fragment fragment = fragmentManager.findFragmentByTag("RecordingRemote");
      fragmentTransaction.remove(fragment);
      fragmentManager.executePendingTransactions();

  }

    }
};

注册:

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

    LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("Recording"));

// ...

}

1 个答案:

答案 0 :(得分:0)

你在整个交易中错过了一个提交。

    fragmentTransaction.remove(fragment);
    fragmentManager.executePendingTransactions();
    fragmentTransaction.commit(); // THIS ONE YOU DON'T HAVE