整體思路:使用FrameLayout作為變暗區(qū)域的Root英岭,并設(shè)置FrameLayout的foreground為黑色不透明的shape,之后就可以修改shape的透明度北救,讓指定區(qū)域變暗荐操。之后通過在子線程中添加延時(shí),使屏幕變化緩慢執(zhí)行珍策,實(shí)現(xiàn)漸變效果托启。
本文結(jié)構(gòu)
- 1.簡單實(shí)現(xiàn)
- 2.在實(shí)現(xiàn)過程中添加延時(shí)效果,讓其變暗有一個(gè)過程攘宙,再逐步恢復(fù)原樣屯耸。
1.簡單實(shí)現(xiàn)
1.1 新建dim.xml
先新建一個(gè)dim.xml文件(/drawable/dim.xml)拐迁,里面放入要用的shape。
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#000000" />
</shape>
注意其中顏色為黑色(#000000)疗绣,沒有指定Alpha通道(透明度)的值线召。如果在這里指定了Alpha通道,如使用#ff000000多矮,該Alpha通道的值(0xff)就會(huì)固定缓淹,無法再通過setAlpha()方法設(shè)置。
1.2 設(shè)置布局文件
將要變暗的區(qū)域放在FrameLayout中塔逃,并設(shè)置 FrameLayout 的 foreground 為上面定義的 dim.xml讯壶。
由于 dim.xml 是不透明的黑色,這里還設(shè)置了tools:foreground=""湾盗,以免在Preview窗口一團(tuán)黑鹏溯。
<FrameLayout
android:id="@+id/fl_forDark"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foreground="@drawable/dim"
tools:foreground=""
>
<android.support.v4.view.ViewPager
android:id="@+id/main_viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
如果在設(shè)置tools:foreground=""時(shí)報(bào)錯(cuò),檢查一下有沒有設(shè)置:
xmlns:tools="http://schemas.android.com/tools"
1.3 java代碼部分
同樣由于 dim.xml 是黑色的淹仑,在初始化時(shí)記得首先把它設(shè)置為透明:
mFrameLayout = (FrameLayout) findViewById(R.id.fl_forDark);
if (mFrameLayout.getForeground()!=null){
mFrameLayout.getForeground().setAlpha(0);
}
然后可以在點(diǎn)擊事件中添加setAlpha()實(shí)現(xiàn)效果丙挽。
mFrameLayout.getForeground().setAlpha(127); //此句添加到第一個(gè)點(diǎn)擊事件中,點(diǎn)擊屏幕變暗
mFrameLayout.getForeground().setAlpha(0); //此句添加到第二個(gè)點(diǎn)擊事件中匀借,點(diǎn)擊屏幕恢復(fù)
2.添加延時(shí)效果
通過實(shí)現(xiàn)上面的代碼發(fā)現(xiàn)颜阐,屏幕變暗與恢復(fù)都是瞬間完成的,顯得突兀吓肋,在實(shí)際開發(fā)過程中可能需要讓其變化有一個(gè)過程凳怨。
2.1 新建一個(gè)Handle對象,在Hanlde調(diào)用改變透明度的方法
Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:
mFrameLayout.getForeground().setAlpha((int)msg.obj);
break;
}
}
};
2.2 在onClick()方法中修改,
先設(shè)置一個(gè)參數(shù)
private int alpha; //用于設(shè)定透明度的參數(shù)
將原來的兩句刪掉是鬼,
mFrameLayout.getForeground().setAlpha(127);
mFrameLayout.getForeground().setAlpha(0);
在用于變暗的onClick()中寫入:
alpha = 0;
new Thread(new Runnable() {
@Override
public void run() {
while (alpha < 127) {
try {
Thread.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message msg = mHandler.obtainMessage();
msg.what = 1;
alpha += 1; //每次加1肤舞,逐漸變暗
msg.obj = alpha;
mHandler.sendMessage(msg);
}
}
}).start();
在用于恢復(fù)的onClick()寫入:
alpha = 127;
new Thread(new Runnable() {
@Override
public void run() {
while (alpha > 0) {
try {
Thread.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message msg = mHandler.obtainMessage();
msg.what = 1;
alpha -= 1; //每次加1,逐漸變暗
msg.obj = alpha;
mHandler.sendMessage(msg);
}
}
}).start();
這樣可以效果了均蜜。