Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> Android自定義邊框背景的Toast

Android自定義邊框背景的Toast

編輯:關於android開發

  在Android程序設計中,有時候我們需要自定義Toast提示信息的背景顏色和邊框顏色,例如下圖:

  默認的Toast無法實現我們所需要的效果,那麼我們只能自定義布局文件,另外Toast的背景形狀是圓角的,所以我們需要自定義Shape文件。

  步驟如下:
  1、在drawable-hdpi下新建一個my_border.xml文件
   <?xml version="1.0" encoding="UTF-8"?>
  <shape xmlns:android="http://schemas.android.com/apk/res/android">
      <solid android:color="#ff0000ff"/>   
      <stroke android:width="1dp" android:color="#FFFFFFFF" />
      <padding android:left="7dp" android:top="7dp"
              android:right="7dp" android:bottom="7dp" />
      <corners android:radius="4dp" />
  </shape>

  2、新建一個布局文件my_toast.xml
  <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="wrap_content" android:layout_height="wrap_content"
      android:background="@drawable/my_border">
      <TextView android:layout_width="wrap_content" android:id="@+id/TextViewInfo"
          android:layout_height="wrap_content" android:text="這是一個自定義背景顏色的提示框"
          android:layout_gravity="center_vertical" android:textColor="#ff00ff00"></TextView>
  </LinearLayout> 
  在此文件中把該布局的背景設為第一步時建立的Shape文件。

  3、Java調用代碼:
  View toastRoot = getLayoutInflater().inflate(R.layout.my_toast, null);
  Toast toast=new Toast(getApplicationContext());
   toast.setView(toastRoot);
  TextView tv=(TextView)toastRoot.findViewById(R.id.TextViewInfo);
  tv.setText("說明:這是一個自定義邊框和底色的提示框。");
  toast.show();

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved