Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android之自定義Toast使用方法

android之自定義Toast使用方法

編輯:關於Android編程

Android系統默認的Toast十分簡潔,使用也非常的簡單。但是有時我們的程序使用默認的Toast時會和程序的整體風格不搭配,這個時候我們就需要自定義Toast,使其與我們的程序更加融合。

使用自定義Toast,首先我們需要添加一個布局文件,該布局文件的結構和Activity使用的布局文件結構一致,在該布局文件中我們需設計我們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="10dp"
android:background="#DAAA"
>
<ImageView android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="10dp"
/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#FFF"
/>
</LinearLayout>

在這個地方要注意,我們給LinearLayout添加的id屬性,在後面的代碼中我們需要使用到。在程序中,我們可以通過如下代碼創建我們自己的Toast:
復制代碼 代碼如下:
public class MainActivity extends Activity
{
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
//獲取LayoutInflater對象,該對象能把XML文件轉換為與之一直的View對象
LayoutInflater inflater = getLayoutInflater();
//根據指定的布局文件創建一個具有層級關系的View對象
//第二個參數為View對象的根節點,即LinearLayout的ID
View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
//查找ImageView控件
//注意是在layout中查找
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.head);
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("自定義Toast演示程序");
Toast toast = new Toast(getApplicationContext());
//設置Toast的位置
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
//讓Toast顯示為我們自定義的樣子
toast.setView(layout);
toast.show();
}
});
}
}

運行效果:
 
囧神的世界你不懂,蟲哥的生活你沒有,只有程序猿的世界大家才知道。程序猿們,為了自己的精彩世界奮斗吧,努力吧!加油……
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved