来自另一个片段的小吃回调

时间:2016-08-08 09:35:29

标签: android android-fragments android-recyclerview snackbar

我有一个带回收者视图的片段(A)。当我按下某个项目时,会显示 DialogFragment (包含该项目的详细信息)。当我按下删除按钮时,该项目被删除并显示片段A(带有更改)。我的问题是如何通知该项目已被删除?我想通过撤消选项显示 Snackbar 。我在谷歌上找不到任何东西..

由于

1 个答案:

答案 0 :(得分:3)

在DialogFragment中定义一个接口:

public interface OnDeletedItem {
        void onDeletedItem(Item deletedItem);
    }

让您的活动实现界面

public class MainActivity
        extends AppCompatActivity
        implements DialogFragment.OnDeletedItem

    @Override
    public void onDeletedItem(Item deletedItem) {

            // get the Fragment A from fragment manager and notify it via public method to show a Snackbar with the Undo option as desired

FragmentA fragmentA = (FragmentA) getFragmentManager().findFragmentByTag("FragmentA");
fragmentA.showSnackbarForDeletedItem(deletedItem); // implement showSnackbarForDeletedItem or similar method in FragmentA
getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

然后,当您按下DialogFragment中的“删除”按钮时:

try {

     ((OnDeletedItem)getActivity()).onDeletedItem(deletedItem);

    } catch (ClassCastException cce) {}