Dialog 常用的用户交互
Dialog 是提示的窗体,默认为当我们点击空白处或者点返回键时Dialog 会消失。如果想要Dialog点击空白区不消失,按返回键时消失。代码如下:
private void showDialog(){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(getString(R.string.save));
dialog.setIcon(R.drawable.ic_launcher);
dialog.setCancelable(false);// 设置点击屏幕和返回键Dialog不消失
dialog.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(DialogInterface arg0, int arg1, KeyEvent arg2) {
//监听返回键在这里关闭Dialog按返回键就能消失
return false;
}
});
dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog aler = dialog.create();
aler.show();
}
在我们自定义Dialog布局中带有输入框,AlertDialog.setView()时软键盘弹不出来怎么解决。代码如下:
private void showSaveDialog() {
Builder dialog = new AlertDialog.Builder(this);
dialog.show();
dialog.setTitle(getString(R.string.save));
final EditSaveView view = new EditSaveView(this);
dialog.setView(view);
//弹出软键盘
dialog.getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
dialog.setConfirmListener(null, new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
自定义Dialog 布局,控制Dialog显示的大小.代码如下:
private void showDialog() {
dialog = new Dialog(context, R.style.CustomDialog);
View view = inflater.inflate(R.layout.equalizer_dialog, null);
mReset = (ImageView) view.findViewById(R.id.main_dailog_reset);
mClose = (ImageView) view.findViewById(R.id.main_dailog_close);
mRoot = (ViewGroup) view
.findViewById(R.id.equalizer_progressbar_parent);
dialog.setContentView(view);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
params.width = ScreenUtil.getWindowsW(context) * 4 / 5;
params.height = ScreenUtil.getWindowsH(context) * 4 / 5;
dialog.getWindow().setAttributes(params);
initEvent();
setProgressbar();
}
通过WindowManager窗体机制来设置Dialog窗体的大小,我们也可以通过样式来设置背景颜色及透明程度,是否有标题,是否浮现在activity之上,是否模糊等属性.样式代码如下:
<style name="CustomDialog" parent="android:style/Theme.Holo.Light.Dialog">
<!-- 背景颜色及透明程度 -->
<item name="android:windowBackground">@android:color/white</item>
<!-- 是否有标题 -->
<item name="android:windowNoTitle">true</item>
<!-- 是否浮现在activity之上 -->
<item name="android:windowIsFloating">true</item>
<!-- 是否模糊 -->
<item name="android:backgroundDimEnabled">true</item>
</style>