代码:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View view){
MyDialogFragmnet myDialogFragmnet = new MyDialogFragmnet();
myDialogFragmnet.show(getFragmentManager(), "dialog");
}
}
activiy_main布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click"
android:text="DialogFragment对话框" />
</RelativeLayout>
MyDialogFragment
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.AlertDialog.Builder;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* 官方推荐使用DialogFragment
* 传统的对话框屏幕切换时 会消失 第一:不会保存用户输入的值 第二:还会报异常
* @author Administrator
*
*/
public class MyDialogFragmnet extends DialogFragment {
// @Override
// public Dialog onCreateDialog(Bundle savedInstanceState) {
// AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
// dialog.setIcon(R.drawable.ic_launcher).setTitle("提示").setMessage("正在下载中...");
// return super.onCreateDialog(savedInstanceState);
// }
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.custom_dialog, container, false);
return view;
}
}
dialog_activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UserName:"/>
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/textView"
android:layout_alignBaseline="@id/textView"
android:hint="请输入用户名"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="@id/editText"
android:text="OK"/>
</RelativeLayout>