一、寫在前面的
在需求上遇到背景設(shè)置透明度還是比較常見(jiàn)的,設(shè)置透明度有幾種方式,但是不同的場(chǎng)景應(yīng)用下,不同的方式可能會(huì)出現(xiàn)一些問(wèn)題。針對(duì)開(kāi)發(fā)過(guò)程中的需求做以下總結(jié)。
二、先看效果圖
圖1、
圖2、

圖3、
圖4

介紹:圖1、藍(lán)色頭部和輸入框背景初始狀態(tài)
圖2、點(diǎn)擊按鈕01,輸入框的透明度不起作用,和title的透明度一樣
圖3、點(diǎn)擊按鈕02,背景透明度設(shè)置正常,但是可能會(huì)對(duì)全局的背景有影響
圖4、點(diǎn)擊按鈕03,背景透明度設(shè)置正常,具體原因代碼注釋有提到
三、再加上代碼
按鈕點(diǎn)擊
public void button01(View view){ // search透明度不起作用 title.setAlpha(0.2f); search.setAlpha(0.8f); } public void button02(View view){ // 在布局中多個(gè)控件同時(shí)使用一個(gè)資源的時(shí)候,這些控件會(huì)共用一個(gè)狀態(tài) // 如果你改變了一個(gè)控件的狀態(tài),其他的控件都會(huì)接收到相同的通知 title.getBackground().setAlpha(51); search.getBackground().setAlpha(153); } public void button03(View view){ // 使用mutate()方法使該控件狀態(tài)不定,這樣不定狀態(tài)的控件就不會(huì)共享自己的狀態(tài)了 title.getBackground().mutate().setAlpha(51); search.getBackground().mutate().setAlpha(153); } 布局:
<?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 android:id="@+id/ll_title" android:layout_width="match_parent" android:layout_height="80dp" android:gravity="center" android:background="#0000ff" android:orientation="horizontal"> <EditText android:id="@+id/et_search" android:layout_width="200dp" android:layout_height="60dp" android:gravity="center" android:hint="輸入框" android:textColorHint="#ffffff" android:background="@drawable/search_title_bg"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:orientation="horizontal"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="01" android:onClick="button01"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="02" android:onClick="button02"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="03" android:onClick="button03"/> </LinearLayout> </LinearLayout>
輸入框背景 search_title_bg
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#000000"/> <corners android:radius="8dp"/> <stroke android:width="1dp" android:color="#666666"/> </shape>
四、寫在后面的
背景透明度設(shè)置比較常見(jiàn),mutate()方法,可以解決背景透明狀態(tài)設(shè)置異常的現(xiàn)象。
新聞熱點(diǎn)
疑難解答
圖片精選