import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
/**
* Created by tangjiangxu on 3/10/17.
*/
public class LoginDialogFragment extends DialogFragment{
/**
* 方法1来实现,重写onCreateView方法
* @param inflater
* @param container
* @param savedInstanceState
* @return
*/
/*@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//点击Dialog之外的地方,不能取消dialog
getDialog().setCanceledOnTouchOutside(false);
//这样设置Dialog不能被取消,无效。需要监听回退键来处理
//getDialog().setCancelable(false);
//去掉Dialog的标题
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
return inflater.inflate(R.layout.fragment_login_dialog, container);
}*/
/**
* 方法2来实现,重写onCreateDialog
* @param savedInstanceState
* @return
*/
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder buidler = new AlertDialog.Builder(getActivity());
//这样设置Dialog不能被取消,无效。需要监听回退键来处理
//buidler.setCancelable(false);
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_login_dialog, null);
final EditText etName = (EditText) view.findViewById(R.id.et_username);
final EditText etPwd = (EditText) view.findViewById(R.id.et_password);
buidler.setView(view);
buidler.setPositiveButton("登录", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (getActivity() instanceof MainActivity) {
String name = etName.getText().toString().trim();
String pwd = etPwd.getText().toString().trim();
//回调Activity中的登录方法
((MainActivity)(getActivity())).login(name, pwd);
}
}
});
buidler.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
return buidler.create();
}
}
取消dialog的背景,设置其为透明
@Override
public void onStart() {
super.onStart();
Dialog dialog = getDialog();
if (dialog != null) {
DisplayMetrics dm = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
if (dialog.getWindow() != null) {
dialog.getWindow().setLayout((int) (dm.widthPixels * 0.8), ViewGroup.LayoutParams.WRAP_CONTENT);
}
}
}