国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

android之自定義Toast使用方法

2020-04-11 12:35:34
字體:
來源:轉載
供稿:網友
Android系統默認的Toast十分簡潔,使用也非常的簡單。但是有時我們的程序使用默認的Toast時會和程序的整體風格不搭配,這個時候我們就需要自定義Toast,使其與我們的程序更加融合。

使用自定義Toast,首先我們需要添加一個布局文件,該布局文件的結構和Activity使用的布局文件結構一致,在該布局文件中我們需設計我們Toast的布局,例如:
復制代碼 代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout_root"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:background="#DAAA"
>
<ImageView android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="10dp"
/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#FFF"
/>
</LinearLayout>

在這個地方要注意,我們給LinearLayout添加的id屬性,在后面的代碼中我們需要使用到。在程序中,我們可以通過如下代碼創建我們自己的Toast:
復制代碼 代碼如下:

public class MainActivity extends Activity
{
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
//獲取LayoutInflater對象,該對象能把XML文件轉換為與之一直的View對象
LayoutInflater inflater = getLayoutInflater();
//根據指定的布局文件創建一個具有層級關系的View對象
//第二個參數為View對象的根節點,即LinearLayout的ID
View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
//查找ImageView控件
//注意是在layout中查找
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.head);
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("自定義Toast演示程序");
Toast toast = new Toast(getApplicationContext());
//設置Toast的位置
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
//讓Toast顯示為我們自定義的樣子
toast.setView(layout);
toast.show();
}
});
}
}

運行效果:
 
主站蜘蛛池模板: 大足县| 磐石市| 公安县| 扶余县| 富顺县| 通许县| 鲜城| 睢宁县| 赤峰市| 日喀则市| 田东县| 八宿县| 新源县| 汤原县| 灵山县| 宜君县| 萍乡市| 芦溪县| 新疆| 通山县| 新泰市| 东乡| 抚顺县| 桑日县| 双鸭山市| 福鼎市| 禄丰县| 平和县| 广汉市| 新干县| 内黄县| 南丹县| 全南县| 布尔津县| 龙井市| 马龙县| 三河市| 都匀市| 秦安县| 金塔县| 德阳市|