如何将Bundle中的MenuItem传递给Android中的Dialog Fragment

时间:2014-09-18 07:37:00

标签: android android-fragments bundle

我需要将MenuItem generateProgress = menu.findItem(R.id.generate_movie);传递给我的DialogFragment newInstance,并在此实例中将Bundle传递给onCreateDialog

public void showGifDialog() {
    DialogFragment newFragment = GenerateGifDialogFragment.newInstance(generateProgress);
    newFragment.show(getFragmentManager(), "generateGif");
}

public static GenerateGifDialogFragment newInstance(MenuItem generateProgress) {
    GenerateGifDialogFragment f = new GenerateGifDialogFragment();
    Bundle args = new Bundle();
    // pass here MenuItem
    f.setArguments(args);

    return f;
}

如何通过内置Android界面?我应该创建一个类并扩展它吗?或者它是更好的方式,比如从getActivity()直接调用菜单和从Fragment类调用findItem?

1 个答案:

答案 0 :(得分:1)

我做了类似的事情,在我的活动中创建了一个方法,然后通过getActivity()访问它。这是一个例子:

private boolean mProgressShown;
private MenuItem mSearchItem;
private SearchView mSearchView;
private View mProgressView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Prepare progress layout for usage later
    mProgressView = LayoutInflater.from(this).inflate(R.layout.progress_icon, null);
    ...
}

public void showProgressIcon() {
    if (mSearchItem != null && !mProgressShown) {
        mProgressShown = true;
        mSearchItem.setActionView(mProgressView);
    }
}

public void hideProgressIcon() {
    if (mSearchItem != null && mProgressShown) {
        mProgressShown = false;
        mSearchItem.setActionView(mSearchView);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    mSearchItem = menu.findItem(R.id.action_search);
    mSearchView = (SearchView) mSearchItem.getActionView();
    ...
}

然后从我的片段中我会打电话:

((MainActivity)getActivity).showProgressIcon();
((MainActivity)getActivity).hideProgressIcon();