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

首頁 > 系統 > Android > 正文

基于自定義Toast全面解析

2019-10-22 18:26:41
字體:
來源:轉載
供稿:網友

Toast一般用來顯示一行文字,用法比較固定:

Toast.makeText(Context context,String message,int duration);

但是有時候想用toast 來顯示復雜的view甚至是帶有圖片的view時這時候就要用到自定義的Toast,自定義Toast主要用到一下幾個方法如圖:

自定義Toast

1.setView()方法用來顯示用戶自定義的view.

2. setGravity()用來確定Toast顯示的位置.

3.setDuration()用來設置Toast顯示的時間長短,只有兩種選擇,LENGTH_SHORT,LENGTH_LONG,都是int型。

4.setText()用來顯示一段文字,但是要注意的時setText()與setView(),不能同時使用不然就會出錯。

下面通過一個完整的代碼來看看如何實現一個自定義的Toast:

Toast_view.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:orientation="vertical"  android:gravity="center">  <ImageView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:src="@drawable/tianjia_p"    android:layout_gravity="center"    />  <TextView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="hello world"    android:layout_gravity="center_horizontal"    android:textSize="20dp"    /></LinearLayout>

Activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="match_parent"  android:layout_height="match_parent"  >  <Button    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:id="@+id/myButton"    android:text="button"    /></LinearLayout>

ToastUtil:

public class ToastUtil {  private static Toast toast;  public static void showToast(int duration,View mview,Context context)  {    if (toast==null) {      toast = new Toast(context);    }    toast.setDuration(duration);    toast.setView(mview);    toast.show();  }}

MainActivity:

public class MainActivity extends AppCompatActivity {private View toast_view;  private Button button;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    LayoutInflater inflater=LayoutInflater.from(this);    toast_view =inflater.inflate(R.layout.toast_view,null);    button=(Button)findViewById(R.id.myButton);    button.setOnClickListener(new View.OnClickListener() {      @Override      public void onClick(View v) {        ToastUtil.showToast(Toast.LENGTH_SHORT,toast_view,getApplicationContext());      }    });  }}

上面的ToastUtil工具類 寫的不好,大家可以自己改寫自己的ToastUtil類。

以上這篇基于自定義Toast全面解析就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 莎车县| 广安市| 东兰县| 常宁市| 阿拉善右旗| 泾阳县| 靖宇县| 棋牌| 郓城县| 灯塔市| 铅山县| 揭阳市| 岳普湖县| 房产| 灵宝市| 金寨县| 梁河县| 南昌市| 石渠县| 黎川县| 平昌县| 大田县| 绥棱县| 肥城市| 麻阳| 高阳县| 原阳县| 治县。| 公主岭市| 都昌县| 佳木斯市| 泉州市| 平南县| 嘉鱼县| 张家界市| 确山县| 额敏县| 大庆市| 通化市| 壶关县| 河曲县|