天天看點

Android中自定義Activity和Dialog的位置大小背景和透明度等

1.自定義activity顯示樣式

先在res/values下建colors.xml檔案,寫入:

[xhtml] view

plaincopy

<?xml version="1.0" encoding="utf-8"?>  

<resources>  

    <!-- 設定透明度為56%(9/16)左右 -->  

    <color name="transparent">#9000</color>       

</resources>    

這個值設定了整個界面的透明度,為了看得見效果,現在設為透明度為56%(9/16)左右。

再在res/values/下建styles.xml,設定程式的風格

<?xml version="1.0" encoding="utf-8"?>    

    <mce:style name="transparent"><!-- 

 設定背景 -->     

        <item name="android:windowbackground">@color/transparent</item>  

        <!-- 設定底層可見 -->     

        <item name="android:windowistranslucent">true</item>  

        <!-- 設定跳轉效果 -->  

        <item name="android:windowanimationstyle">@+android:style/animation.translucent</item>     

--></mce:style><style name="transparent" mce_bogus="1"> 設定背景 -->     

    </style>   

</resources>  

注:mce部分為發帖是自動生成的,實際不需要。

最後一步,把這個styles.xml用在相應的activity上。即在androidmanifest.xml中的任意<activity>标簽中添加 

android:theme = "@style/transparent" 

如果想設定所有的activity都使用這個風格,可以把這句标簽語句添加在<application>中。 

最後運作程式,哈哈,是不是發現整個界面都被蒙上一層半透明了。最後可以把背景色#9000換成#0000,運作程式後,就全透明了,看得見背景下的所有東西可以卻都操作無效。呵呵.... 

2.将activity以dialog的形式顯示并自定義樣式

先在res/drawable下建bgconfig.xml檔案,寫入:

<shape xmlns:android="http://schemas.android.com/apk/res/android">    

    <solid android:color="#ffffff" />    

    <stroke android:width="3dp" color="#000000" />    

    <corners android:radius="3dp" />    

    <padding android:left="3dp" android:top="3dp" android:right="3dp"    

        android:bottom="3dp" />  

</shape>   

[xhtml]

view plaincopy

        <!-- 設定樣式 -->  

    <mce:style name="theme.myactivity" parent="android:style/theme.dialog" mce_bogus="1" mce_bogus="1"><!-- 

        <item name="android:windowbackground">@drawable/bgconfig</item> 

--></mce:style><style name="theme.myactivity" parent="android:style/theme.dialog" mce_bogus="1" mce_bogus="1" mce_bogus="1">     <item name="android:windowbackground">@drawable/bgconfig</item>  

    </style>  

如果想設定所有的activity都使用這個風格,可以把這句标簽語句添加在<application>中。

3.設定視窗大小和位置

[java] view

windowmanager m = getwindowmanager();    

       display d = m.getdefaultdisplay();  //為擷取螢幕寬、高    

       layoutparams p = getwindow().getattributes();  //擷取對話框目前的參數值    

       p.height = (int) (d.getheight() * 1.0);   //高度設定為螢幕的1.0   

       p.width = (int) (d.getwidth() * 0.7);    //寬度設定為螢幕的0.8   

       p.alpha = 1.0f;      //設定本身透明度  

       p.dimamount = 0.0f;      //設定黑暗度  

       getwindow().setattributes(p);     //設定生效  

       getwindow().setgravity(gravity.right);       //設定靠右對齊 

繼續閱讀