我正在尝试显示DialogFragment
询问用户他的名字,我需要将此字符串返回到我的主要活动。
我在Android指南后创建了一个自定义对话框片段:http://developer.android.com/guide/topics/ui/dialogs.html#CustomLayout
在我的代码中,为了响应用户点击肯定按钮,我可以在我的主要活动中调用一个函数:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.textdialog, null)).setPositiveButton("OK", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int id) {
((mainActivity)getActivity()).doPositiveClick();
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
((mainActivity)getActivity()).doNegativeClick();
}
});
return builder.create();
}
其中R.layout.textdialog是:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/textdraw"
android:inputType="textEmailAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="introduce text" />
</LinearLayout>
我的问题是,如何在对话框片段中获取用户编写的文本并将其发送回我的主要活动?
谢谢!
答案 0 :(得分:4)
好吧,我解决了自己(但不确定这是不是更好的方式)
我在onCreateDialog
。
将视图保存在变量中:
View v= inflater.inflate(R.layout.textdialog, null);
将edittext保存在变量中:
final EditText ed=(EditText)v.findViewById(R.id.textdraw);
当用户点击肯定按钮时,发回edittext变量中的值:
getActivity()).doPositiveClick(ed.getText().toString());
完整代码在这里:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View v= inflater.inflate(R.layout.textdialog, null);
// reference to the edittext
final EditText ed= (EditText)v.findViewById(R.id.textdraw);
builder.setView(v).setPositiveButton("OK", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int id) {
((mainActivity)getActivity()).doPositiveClick(ed.getText().toString());
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
((mainActivity)getActivity()).doNegativeClick();
}
});
return builder.create();
}
和主要活动中的代码:
public void doPositiveClick(String ed){
Toast.makeText(this, "Hi, "+ed, Toast.LENGTH_SHORT).show();
}