由于项目需要,在用户返回信息时,弹出一个透明对话框,所以自己就自定义一个Dialog,在此分享给大家,有好的建议和想法可以联系我。
package com.android.transparentdialog;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
Dialog mReceivedDialog;
View alertView;
ImageView imageView;
TextView textView;
WindowManager mWindowManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
// 获得WindowManager的两种方法
mWindowManager = getWindowManager();
// mWindowManager=(WindowManager)
// getSystemService(Context.WINDOW_SERVICE);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
mReceivedDialog = createAlertDialog(R.drawable.zzz_ebook,
getString(R.string.text_context));
mReceivedDialog.show();
}
});
}
// 自定义布局初始化
private View getAlertView(int img, String str) {
if (alertView != null) {
alertView = null;
}
alertView = LayoutInflater.from(this).inflate(R.layout.zzz_alert, null);
imageView = (ImageView) alertView.findViewById(R.id.zzz_alert_img);
textView = (TextView) alertView.findViewById(R.id.zzz_alert_text);
imageView.setImageResource(img);
textView.setText(str);
return alertView;
}
// 创建自定义dialog
private Dialog createAlertDialog(int img, String str) {
final Dialog receivedDialog = new Dialog(this, R.style.dialog);
Window window = receivedDialog.getWindow();
// 设置dialog透明度
/*
* WindowManager.LayoutParams lp = window.getAttributes(); // 设置透明度为0.3
* lp.alpha = 0.01f; window.setAttributes(lp);
*/
// 设置点击Dialog外部任意区域关闭Dialog
receivedDialog.setCanceledOnTouchOutside(false);
receivedDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
window.setBackgroundDrawableResource(android.R.color.transparent);
// 设置dialog类型但必须给予权限
window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
// 设置dialog出现的位置
// window.setGravity(Gravity.START);//center,BOTTOM....
// 设置dialog背景模糊
/*
* window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
* WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
*/
View view = getAlertView(img, str);
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
receivedDialog.dismiss();
}
});
receivedDialog.setContentView(view, new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
// dialog宽度铺面整个屏幕
Display display = mWindowManager.getDefaultDisplay();
WindowManager.LayoutParams lp = window.getAttributes();
lp.width = (int) (display.getWidth());
window.setAttributes(lp);
return receivedDialog;
}
}
项目分享地址如下: