如何从静态片段 class 获取数据?

How to get data from static fragment class?

我在扩展 DialogFragment 的静态 class 片段中有一个编辑文本。我需要从片段中的 edittext 获取用户输入。我尝试实例化容器 activity 并传递值,但它不起作用,因为我认为我需要将其设为最终状态。请参阅下面的静态代码 class:

public class DetailDaily extends BaseActivity implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {
        ...................
        ..................
        String name;
        ........
public static class DialogCreater extends DialogFragment {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final DetailDaily dd = new DetailDaily();
            int title = getArguments().getInt("Title");
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            // Set the dialog title
            switch (title) {
                case 1:
                    ....................................
                case 2:
                    final LayoutInflater inflater = getActivity().getLayoutInflater();
                    final View mView = inflater.inflate(R.layout.edit_dialog, null);
                    builder.setView(mView)
                            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int id) {
                                    EditText userInput = (EditText) mView.findViewById(R.id.dialogEdit);
                                    dd.name = userInput.toString(); 
                                }
                            })
                            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            });
                    break;
            }


            return builder.create();
        }
    }

如何从静态中读取 userInput class?

首先,除非您确实需要在 Activity 中声明 DialogFragment,否则请将其移至单独的 class(不一定是静态的)。此外,您到底为什么要在 FragmentDialog 中创建一个 Activity 实例?

其次,调用DialogFragment的标准方法是使用newInstance()函数。您可以传入回调接口以将结果传递给您的 Activity.

请查看 Android documentation 示例。

public static interface Callback {
    public void onResult(String result);
}

static MyDialogFragment newInstance(MyDialogFragment.Callback callback) {
    MyDialogFragment f = new MyDialogFragment();

    f.setCallback(callback);

    return f;
}

你可以打电话mCallback.onResult(editTextResult);当你有什么想return到Activity

然后用以下方式给您的 DialogFragment 打电话:

// FragmentTransaction boilerfluff here
DialogFragment newFragment = MyDialogFragment.newInstance(new MyDialogFragment.Callback() {
    @Override
    public void onResult(String result) {
        // Do stuff
    }
});
newFragment.show(ft, "dialog");