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

时间:2015-08-14 14:15:25

标签: java android android-fragments static-class

我在静态类的片段中有一个edittext,它扩展了DialogFragment。我需要从片段内的edittext获取用户输入。我尝试实例化容器活动并传递值,但它不起作用,因为我需要让它最终,我想。请参阅下面的静态类代码:

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?

1 个答案:

答案 0 :(得分:1)

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

其次,调用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);,可以致电Activity

然后通过以下方式致电DialogFragment

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