一、自定義對話框樣式:
在styles.xml中
<!-- 定義對話框樣式 -->
<style name="Dialog" parent="android:style/Theme.Dialog">
<item name="android:windowBackground">@android:color/transparent</item
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
</style>
WindowBackground為透明,因為要用到自定義的布局,所以必須要把系統(tǒng)的背景顏色設置為透明;WindowNoTitle為true,設置為無標題,因為布局完全是自己自定義的了,WindowIsFloating為true,浮于其他界面之上。好了,這樣就簡單設置了自定義對話框的樣式了。
二、自定義對話框布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
.
.
.
</LinearLayout>
三、創(chuàng)建Dialog,并關聯(lián)自定義的樣式和布局:
final Dialog customDialog = new Dialog(this, R.style.Dialog);
View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_custom, null);
TextView btn_update = (TextView) dialogView.findViewById(R.id.tv_update);
TextView btn_cancel = (TextView) dialogView.findViewById(R.id.tv_cancel);
//將自定義布局加載到dialog上
customDialog.setContentView(dialogView);
btn_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
customDialog.cancel();
}
});
btn_update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "點擊了確定", Toast.LENGTH_SHORT).show();
}
});
//設置點擊dialog外是否可以取消
customDialog.setCancelable(false);
customDialog.show();
到這里就完成了自定義Dialog了,最后還不完美,還可以設置Dialog的顯示大小和位置,
//獲得dialog的window窗口
Window window = customDialog.getWindow();
//設置dialog在屏幕中間
window.setGravity(Gravity.CENTER);
//獲得window窗口的屬性
WindowManager.LayoutParams lp = window.getAttributes();
//設置窗口高度為包裹內容
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
//寬度設置為屏幕的0.7
Display defaultDisplay = getWindowManager().getDefaultDisplay();
lp.width = (int) (defaultDisplay.getWidth() * 0.7);
//將設置好的屬性set回去
window.setAttributes(lp);
這里我把Dialog居中(Gravity.CENTER)顯示了,當然還可以顯示在底部等其他位置;然后就是顯示寬和高了,當然要先獲取屏幕的窗口大小才能設置其寬高。