Android執行個體-手機安全衛士(四十)-自訂多士(二)(配置樣式、背景)

來源:互聯網
上載者:User

標籤:

一、

  自訂Toast的布局、背景等

二、代碼實現

  1、在res檔案夾下的layout檔案夾中建立布局檔案(Android xml file,取名phone_add_toast),用於定義要顯示的Toast的布局方式;

  2、根據設計要求自訂的Toast布局為左右的水平線性布局,寬高均為包裹內容,左邊為圖片,右邊為歸屬地資訊文本(由于歸屬地資訊會根據號碼不同而改變,因此可為其設定id(tv_phone_add_toast));

    (1)圖片採用<ImageView>組件,通過android:src屬性載入圖片資源,寬高均為包裹內容;

    (2)文本採用<TextView>組件,寬高均為包裹內容,設定其id(tv_phone_add_toast)。

自訂的Toast布局檔案:

 1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3     android:layout_width="wrap_content" 4     android:layout_height="wrap_content" 5     android:orientation="horizontal" 6     android:gravity="center_vertical"> 7  8     <ImageView 9         android:layout_width="wrap_content"10         android:layout_height="wrap_content"11         android:src="@android:drawable/ic_menu_search" />12     13     <TextView14         android:id="@+id/tv_phone_add_toast" 15         android:layout_width="wrap_content"16         android:layout_height="wrap_content"17         android:text="號碼歸屬地"/>18 19 </LinearLayout>
View Code

 

  3、在“顯示號碼歸屬地”服務類(ShowPhoneAddService)中定義一個View對象的成員變數(取名view),用於載入布局,(為防止重名,修改原來的TextView對象名稱為toast_phone_add);

  4、在自訂Toast方法中,刪去或注釋建立視窗參數WindowManager.LayoutParams對象前的有關view的語句。

    (1)通過View對象(view)的inflate(Context context, int resource, ViewGroup root)方法將2中定義的Toast布局檔案載入至View對象中,參數context為上下文(此處是this),resource為需要載入的布局檔案資源id,root為父容器(此處為null);

    (2)通過View對象(view)的setBackgroundResource(int resid)、setBackgroundColor(int color)等方法載入背景圖片、背景顏色等屬性,最佳化UI;

    (3)顯示歸屬地資訊的TextView對象(toast_phone_add)通過View對象(view)的findViewById(int id)方法找到自訂Toast布局檔案中的TextView組件,並強轉;

    (4)通過TextView對象(toast_phone_add)的setText(CharSequence text)將傳入自訂Toast方法的String型別參數(phoneAdd)載入上去。

Toast方法中載入自訂布局和相關設定的代碼:

1 view = View.inflate(this, R.layout.phone_add_toast, null);2         view.setBackgroundColor(Color.BLUE);3         toast_phone_add = (TextView) view.findViewById(R.id.tv_phone_add_toast);4         toast_phone_add.setText(phoneAdd);    
View Code

 

Android執行個體-手機安全衛士(四十)-自訂多士(二)(配置樣式、背景)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.