android 自己定義dialog並實現失去焦點(背景透明)的功能
前言:因為在項目中須要用到更新顯示動畫的需求,所以想到了dialog,自己定義dialog不難。網上教程非常多,可是在實現dialog背景透明的需求時,遇到了一點問題。網上的一些方法在我的機器上並沒有實現,僅僅能曲折中找到了還有一個方法實現。盡管有點麻煩。但畢竟效果不錯。
此方法寫在這裏,一是和各位分享,二是做個記錄,留待以後需求。
不說了,上代碼:
以下是dialog自己定義布局文件,是運行任務用的,參考就可以。
<?xml version="1.0" encoding="utf-8"?
> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="運行中" android:textSize="18sp" /> <ImageView android:id="@+id/dialog_image" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_gravity="center" /> </LinearLayout>
自己定義dialog,運行任務的代碼去掉了,能夠加在onCreate()中。
/** * 運行狀態的對話框形式 * @author Administrator * */ class MyDialog extends Dialog{ ImageView imageView; public MyDialog(Context context) { super(context); // TODO Auto-generated constructor stub } public MyDialog(Context context,int theme) { super(context, theme); // TODO Auto-generated constructor stub } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); //去掉activity標題 requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.dialog); //設置標題 imageView = (ImageView)findViewById(R.id.dialog_image); } }
在實現之前。實驗了dialog設置flag的方法,有人說能夠,可是我並沒有實現。也把代碼留下,以作參考:
//使dialog失去焦點 dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE); dialog.setCanceledOnTouchOutside(true);
真正實現的方法是使用style實現的,這個須要兩個資源文件,一個color,一個style。
<color name="transparent">#00000000</color>
<style name="dialog" parent="@android:style/Theme.Dialog"> <item name="android:windowFrame">@null</item><!--邊框--> <item name="android:windowIsFloating">true</item><!--是否浮如今activity之上--> <item name="android:windowIsTranslucent">false</item><!--半透明--> <item name="android:windowNoTitle">true</item><!--無標題--> <item name="android:windowBackground">@color/transparent</item><!--背景透明--> <item name="android:backgroundDimEnabled">false</item><!--模糊--> </style>
設置好資源文件之後。在調用時生成實例代碼例如以下:
MyDialog dialog = new MyDialog(this,R.style.dialog); dialog.show();
至此完成。
參考資料:http://www.cnblogs.com/windlivefamily/articles/2133956.html
android 自己定義dialog並實現失去焦點(背景透明)的功能