Android---自定义Toast
生活随笔
收集整理的這篇文章主要介紹了
Android---自定义Toast
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1、Toast類包含一個(gè)靜態(tài)(static)方法makeText(),它可以創(chuàng)建一個(gè)標(biāo)準(zhǔn)的Toast顯示窗口。一旦創(chuàng)建了一個(gè)Toast,就可以調(diào)用它的show()方法顯示它。
makeText()方法需要要三個(gè)參數(shù):
1》應(yīng)用程序上下文;
2》要顯示的文本消息;
3》該Toast的顯示時(shí)長(zhǎng)(Toast.LENGTH_LONG / ?Toast.LENGTH_SHORT);
代碼如下:
Toast toast = Toast.makeText(MainActivity.this, "Hello World, this is a toast", Toast.LENGTH_LONG);toast.show(); 效果如下:
2、自定義Toast
2.1、使用setGravity方法改變Toast的顯示位置
Toast toast = Toast.makeText(MainActivity.this, "Hello World, this is a toast", Toast.LENGTH_LONG);//底部toast.setGravity(Gravity.BOTTOM, 0, 0);toast.show();
效果如下:
//Toast toast = Toast.makeText(MainActivity.this, "Hello World, this is a toast", Toast.LENGTH_LONG);//頂部toast.setGravity(Gravity.TOP, 0, 0);LinearLayout ll = new LinearLayout(this);ll.setOrientation(LinearLayout.VERTICAL);ImageView iv = new ImageView(this);iv.setImageResource(R.drawable.main_logo);TextView tv = new TextView(this);tv.setText("這是用代碼自定義的Toast...");int height = LinearLayout.LayoutParams.WRAP_CONTENT;int width = LinearLayout.LayoutParams.MATCH_PARENT;ll.addView(iv, height, width);//將ImageView添加到LinearLayoutll.addView(tv, height, width);//將TextView添加到LinearLayouttoast.setView(ll);//將LinearLayout設(shè)置為toast的顯示內(nèi)容toast.show();
2.3、自定義布局來呈現(xiàn)一個(gè)更加復(fù)雜或者視覺效果更好的界面(建議使用該方法,代碼更加簡(jiǎn)潔,布局也更加直觀)
1》首先定義一個(gè)Toast的布局:toast_layout.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/toast_layout_root"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><ImageViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:src="@drawable/main_logo"/><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:text="這是用布局文件自定義的Toast"/></LinearLayout>
//Toast toast = Toast.makeText(MainActivity.this, "Hello World, this is a toast", Toast.LENGTH_LONG);//頂部toast.setGravity(Gravity.TOP, 0, 0);//獲取LayoutInflater對(duì)象,該對(duì)象能把XML文件轉(zhuǎn)換為與之一致的View對(duì)象LayoutInflater inflater = getLayoutInflater();//根據(jù)指定的布局文件創(chuàng)建一個(gè)具有層級(jí)關(guān)系的View對(duì)象//第二個(gè)參數(shù)為View對(duì)象的根節(jié)點(diǎn),即LinearLayout的IDView toast_layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));//讓Toast顯示為我們自定義的樣式toast.setView(toast_layout);toast.show();
效果同2.2
總結(jié)
以上是生活随笔為你收集整理的Android---自定义Toast的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android---AlertDialo
- 下一篇: Android 动画(一)---布局动画