歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android自定義Toast

Android自定義Toast

日期:2017/3/1 9:58:26   编辑:Linux編程

Android系統自帶的Toast可能不是那麼給力,有時候我們需要自定義,先來一個效果圖

步驟如下:

1 定義Toast的樣式 toast.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/hahahahhahah"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/black"
android:padding="6dp" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/app_name"
android:src="@drawable/android" >
</ImageView>

<TextView
android:id="@+id/toastTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="4dp"
android:text="這是標題欄"
android:textColor="@color/white"
android:textIsSelectable="true"
android:textSize="20sp" />
</LinearLayout>

<TextView
android:id="@+id/toastTextView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"
android:paddingBottom="4dp"
android:text="這是要顯示的內容"
android:textColor="@color/white"
android:textIsSelectable="true"
android:textSize="12sp" />

</LinearLayout>

2 自定義Toast,引用我們自己的布局

View contentView = (LinearLayout) LayoutInflater
.from(this).inflate(R.layout.toast, null);
Toast toast=new Toast(this);
toast.setGravity(Gravity.CENTER,0,0);
toast.setView(contentView);
toast.setDuration(Toast.LENGTH_LONG);
toast.show();

這樣就顯示出剛才看到的效果了,大家可以在加入監聽器等其他的內容

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved