话不多说,代码:
XML布局文件,只是一个Demo,所以就一个Button.
<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:id="@+id/button_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/button_text" />
</RelativeLayout>
JAVA代码:
package com.example.dialog_alpha_demo;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity extends Activity {
private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) this.findViewById(R.id.button_id);
mButton.setOnClickListener(listener);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
View.OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ShowDialog();
}
};
private void ShowDialog() {
AlertDialog mDialog = new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher).setTitle("温馨提示")
.setMessage("透明对话框")
.setPositiveButton("确定", null).create();
// 获取对话框的Window对象
Window mWindow = mDialog.getWindow();
WindowManager.LayoutParams lp = mWindow.getAttributes();
// 透明度的范围为:0.0f-1.0f;0.0f表示完全透明,1.0f表示完全不透明(系统默认的就是这个)。
lp.alpha = 0.35f;
//设置对话框在屏幕的底部显示,当然还有上下左右,任意位置
//mWindow.setGravity(Gravity.LEFT);
mWindow.setGravity(Gravity.BOTTOM);
/*
*
* 这里是设置偏移量,这里的x,y并不是相对于屏幕的绝对坐标,而是相对于对话框在中心位置(默认的对话框一般显示在屏幕的中心)而言的
lp.x = -20;// 设置水平偏移量
lp.y = -90;// 设置竖直偏移量
*/
// 设置Window的属性
mWindow.setAttributes(lp);
mDialog.show();
}
}
显示结果为: