android通知控件

老羅視頻學習筆記。


通知有兩種,一種是Toast Notification通知,一種是StatusNotification。


一.ToastNotification通知。

1)普通的Toast通知。

//第一種寫法
				//Toast.makeText(ToastNotificationActivity.this, "這是普通的Toast通知", Toast.LENGTH_SHORT).show();
				//第二種寫法
				Toast toast = Toast.makeText(ToastNotificationActivity.this, "這是普通的Toast通知", Toast.LENGTH_SHORT);
				toast.show();

第一個參數是傳遞上下文的context對象。第二個參數是通知的內容。第三個參數設置Toast顯示的時間是長還是短。


2)可以設置Toast位置的通知。

Toast toast = Toast.makeText(ToastNotificationActivity.this, "這是可以設置位置的Toast通知", Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();

setGravity就是設置toast的位置,center爲在正中心。


3)自定義一個Toast顯示。

那麼首先要自定義一個xml佈局文件imagetoast.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textviewintoast"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="TextView" />
<ImageView 
     android:id="@+id/imageintoast"
     android:padding="10dp"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"></ImageView>
</LinearLayout>

然後在java文件中定義一個佈局對象來加載這個佈局。


//定義一個Toast對象
				Toast toast = new Toast(ToastNotificationActivity.this);
				//定義一個view對象,加載imagetoast佈局
				View view = LayoutInflater.from(ToastNotificationActivity.this).inflate(R.layout.imagetoast, null);
				//給imageView加載圖片
				ImageView imageView = (ImageView)view.findViewById(R.id.imageintoast);
				imageView.setImageResource(R.drawable.tip);
				//給textview設置字體
				TextView textView = (TextView)view.findViewById(R.id.textviewintoast);
				textView.setTextSize(20);
				textView.setText("這個是自定義的toast哦");
				
				//設置toast的位置
				toast.setGravity(Gravity.CENTER, 0, 0);
				//設置Toast顯示的時間長短
				toast.setDuration(Toast.LENGTH_SHORT);
				//設置toast的佈局
				toast.setView(view);
				toast.show();


特別要注意的是ImageView imageView = (ImageView)view.findViewById(R.id.imageintoast);這一句必須要寫view.findViewById,否則會崩潰。因爲通過控件的ID獲取控件對象時,必須要先加載佈局纔可以獲取,否則會崩潰。這段代碼不和之前的代碼那樣,靜態加載佈局setContentView。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章