android toast的使用
今天,沒有什么可以寫的,在網(wǎng)上查找資料,發(fā)現(xiàn)toast有很多知識點(diǎn),所以記錄一下。
Toast
Toast是為了給當(dāng)前視圖顯示一個浮動的顯示塊,它永遠(yuǎn)不會獲得焦點(diǎn)。一般用于提示一些不那么引人注目,但是又希望用戶看見的消息,無需用戶自己維護(hù)它的消失。
如果只是提示簡單的信息,使用Android為Toast提供的兩個靜態(tài)的方法最為方便,它們會返回一個Toast對象,如果需要顯示,只需要調(diào)用show()方法顯示即可,下面是這兩個方法的簽名:
- static Toast makeText(Context context,int resId,int duration).
- static Toast makeText(Context context,CharSequence text,int duration)
上面兩個方法,參數(shù)大致相同,一個上下文對象Context,一個顯示的消息來源,一個設(shè)置持續(xù)時(shí)間。消息來源可以指定String資源,使用<string.../>標(biāo)簽在XML資源文件中定義,還可以指定一個字符串用于消息展示。最后的duration參數(shù)設(shè)置了Toast的持續(xù)時(shí)間,一般使用Toast自帶的兩個整形的常量:LENGTH_LONG(1,時(shí)間稍長)、LENGTH_SHORT(0,時(shí)間稍短),針對不同的使用場景,選擇不用的持續(xù)時(shí)間。
Toast消息的默認(rèn)顯示位置在屏幕的中間偏下,Android也為開發(fā)者提供了方法設(shè)置Toast消息的位置,使用setGravity(int gravity, int xOffset, int yOffset)方法即可設(shè)置,它有三個參數(shù),gravity設(shè)置一個重力方向,另外兩個設(shè)置水平和垂直方向的偏移量
接下來介紹toast的三種效果
1.默認(rèn)效果:
代碼:
Toast.makeText(getApplicationContext(), "默認(rèn)Toast樣式",
? ???Toast.LENGTH_SHORT).show();
2.自定義顯示位置效果:
代碼:
toast = Toast.makeText(getApplicationContext(),
? ???"自定義位置Toast", Toast.LENGTH_LONG);
? ?toast.setGravity(Gravity.CENTER, 0, 0);
? ?toast.show();
自定義消息
無論是從美觀的角度、還是用戶視覺體驗(yàn)的角度,很多時(shí)候都不僅僅需要顯示一簡單的文本信息。如果需要顯示用戶自定義的消息,那么就不能使用上面介紹的靜態(tài)方法來得到一個Toast對象,而是需要使用Toast的構(gòu)造方法進(jìn)行初始化,然后對相應(yīng)的屬性進(jìn)行設(shè)置。一般對于自定義布局的顯示,會使用XML定義好一個布局文件,這樣清晰明朗。
步驟如下:
下面通過一個示例展示自定義布局在Toast中的顯示:
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="8dp"android:background="#DAAA"><ImageView android:src="@drawable/ic_launcher"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginRight="8dp"/><TextView android:id="@+id/text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textColor="#FFF"/> </LinearLayout>Toast消息的顯示代碼:
btnCustomToast.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {View view=LayoutInflater.from(MainActivity.this).inflate(R.layout.toast_layout,null );TextView tv=(TextView)view.findViewById(R.id.text);tv.setText("自定義提示Toast");Toast toast=new Toast(MainActivity.this);toast.setView(view);toast.show();}});效果展示:
這是在網(wǎng)上搜索到的toast的資料的整理的,大家有興趣自己可以去查找資料。
android toast的使用就講完了。
就這么簡單。
總結(jié)
以上是生活随笔為你收集整理的android toast的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android textView设置粗体
- 下一篇: android 解决小米手机上选择照片路