android - 如何等到 fragment 被删除

标签 android android-fragments fragmenttransaction

我有一个包含动态 fragment 的 Activity 。我需要运行一些代码 after 一个 fragment 被删除但是 remove(myFragment).commit() 是异步执行的,我不知道 fragment 何时被删除。这是我的代码:

final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.remove(myFragment).commit();
//wait until the fragment is removed and then execute rest of my code

来自文档:

public abstract int commit ()

Schedules a commit of this transaction. The commit does not happen immediately; it will be scheduled as work on the main thread to be done the next time that thread is ready.

最佳答案

如果您使用 fragment 的 onDetach 方法调用 Activity 并告诉它已完成,会怎样?

class MyFrag extends Fragment {

    private Activity act;

    @Override
    public void onAttach(Activity activity) {
        act = activity;
    }

    @Override
    public void onDetatch() {
        act.fragGone();
    }
}

在 Activity 中:

public void fragGone() {
    //do something, update a boolean, refresh view, etc.
}

关于android - 如何等到 fragment 被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16842774/

相关文章:

android - 设备重新联机后,Google 云消息传递 (GCM) 无法传送

android - 将对象作为参数从 Activity 传递到 fragment 的问题

javascript - Android CloudRail 品牌网站失败 - "Unexpected token )"(community.js 第 18 行)

C# DateTime 到字符串问题

java - 如何对带有类的 fragment 使用 instanceof 运算符

android - 调用 Activity.onSaveInstanceState() 后的 commit() fragment 事务

android - Fragment交易到底在哪里实现?

Java FragmentTransaction 类

android - 在待机状态下拥有多个 UDP 数据报套接字有意义吗? "simultaneous"数据包是否被内核丢弃或排队?

android - (已弃用) fragment onOptionsItemSelected 未被调用