Android---自定义Toast
生活随笔
收集整理的這篇文章主要介紹了
Android---自定义Toast
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、Toast類包含一個靜態(static)方法makeText(),它可以創建一個標準的Toast顯示窗口。一旦創建了一個Toast,就可以調用它的show()方法顯示它。
makeText()方法需要要三個參數:
1》應用程序上下文;
2》要顯示的文本消息;
3》該Toast的顯示時長(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設置為toast的顯示內容toast.show();
2.3、自定義布局來呈現一個更加復雜或者視覺效果更好的界面(建議使用該方法,代碼更加簡潔,布局也更加直觀)
1》首先定義一個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對象,該對象能把XML文件轉換為與之一致的View對象LayoutInflater inflater = getLayoutInflater();//根據指定的布局文件創建一個具有層級關系的View對象//第二個參數為View對象的根節點,即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
總結
以上是生活随笔為你收集整理的Android---自定义Toast的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android---AlertDialo
- 下一篇: Android 动画(一)---布局动画