歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android之定制自己的Toast

Android之定制自己的Toast

日期:2017/3/1 11:09:50   编辑:Linux編程

用慣了Toast簡單顯示文本的朋友大概都沒怎麼注意使用定制的Toast可以吸引別人的眼球吧,下面我們來演示一個小例子:

1.toast_view.xml 自定義Toast的View

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout
  3. xmlns:Android="http://schemas.android.com/apk/res/android"
  4. android:orientation="vertical"
  5. android:layout_width="fill_parent"
  6. android:layout_height="fill_parent">
  7. <ImageView android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:src="@drawable/icon"/>
  10. </LinearLayout>

2.測試類

  1. package com.zhf.toast;
  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.os.Bundle;
  5. import android.view.Gravity;
  6. import android.view.LayoutInflater;
  7. import android.view.View;
  8. import android.widget.Toast;
  9. /**
  10. * 定制一個自己的Toast
  11. * @author Administrator
  12. *
  13. */
  14. public class ToastAdvancedDemoActivity extends Activity {
  15. /** Called when the activity is first created. */
  16. @Override
  17. public void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.main);
  20. Toast toast=new Toast(this);
  21. LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  22. View toastView=inflater.inflate(R.layout.toast_view, null);
  23. toast.setGravity(Gravity.CENTER, 0, 0);//Toast顯示的位置
  24. toast.setView(toastView);//定制Toast
  25. toast.show();
  26. }
  27. }

效果圖如下,大家可以根據自己應用程序的需要顯示不同的View

Copyright © Linux教程網 All Rights Reserved