Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自訂 Dialog 三步驟:打造居中顯示圖片的彈出視窗

編輯:關於 Android 開發

Android 自訂 Dialog 三步驟:打造居中顯示圖片的彈出視窗

做 Android 應用時,自訂 Dialog 幾乎是必備技能,因為系統預設的 Dialog 樣式往往與自家應用的風格不相符。其實自訂 Dialog 只需要三個步驟:

1、重寫一個自訂的 Dialog Java 類別
2、準備自訂版面檔,並在 style.xml 中設定一個 Dialog Theme
3、在使用處呼叫

步驟一:建立 CustomPopDialog2.java

 import android.app.Dialog; import android.content.Context; import android.graphics.Bitmap; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager.LayoutParams; import android.widget.ImageView; /** * 該自定義Dialog應用在:彈出框居中顯示圖片,點擊其他區域自動關閉Dialog * * @author SHANHY(365384722@QQ.COM) * @date 2015年12月4日 */ public class CustomPopDialog2 extends Dialog { public CustomPopDialog2(Context context) { super(context); } public CustomPopDialog2(Context context, int theme) { super(context, theme); } public static class Builder { private Context context; private Bitmap image; public Builder(Context context) { this.context = context; } public Bitmap getImage() { return image; } public void setBitmap(Bitmap image) { this.image = image; } public CustomPopDialog2 create() { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); final CustomPopDialog2 dialog = new CustomPopDialog2(context,R.style.Dialog); View layout = inflater.inflate(R.layout.dialog_share_qrcode, null); dialog.addContentView(layout, new LayoutParams( android.view.ViewGroup.LayoutParams.WRAP_CONTENT , android.view.ViewGroup.LayoutParams.WRAP_CONTENT)); dialog.setContentView(layout); ImageView img = (ImageView)layout.findViewById(R.id.img_qrcode); img.setImageBitmap(getImage()); return dialog; } } } 

這裡簡單說明一下:自訂 Dialog 需要準備一個自己的 View 版面檔,重點在於 create() 方法——本範例就是直接顯示一張圖片。

步驟二:自訂版面檔並在 style.xml 加入 Theme

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:id="@+id/rootLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center"> <ImageView android:id="@+id/img_qrcode" android:layout_width="wrap_content" android:layout_height="wrap_content" android:contentDescription="二維碼" /> </LinearLayout>
 <style name="Dialog" parent="android:style/Theme.Dialog"> <item name="android:background">#00000000</item> <item name="android:windowBackground">@android:color/transparent</item> <item name="android:windowNoTitle">true</item> <item name="android:windowIsFloating">true</item> </style>

步驟三:使用自訂的 Dialog

 Bitmap bitmap = xxxxx;// 這裡是獲取圖片Bitmap,也可以傳入其他參數到Dialog中 CustomPopDialog2.Builder dialogBuild = new CustomPopDialog2.Builder(context); dialogBuild.setImage(bitmap); CustomPopDialog2 dialog = dialogBuild.create(); dialog.setCanceledOnTouchOutside(true);// 點擊外部區域關閉 dialog.show();

透過 setCanceledOnTouchOutside(true),使用者點擊彈窗外區域就能關閉視窗。最終效果如下圖:

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved