歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android之Notification實現

Android之Notification實現

日期:2017/3/1 10:49:41   编辑:Linux編程

在我們的相應程序運行的時候為了不打斷當前程序的運行,我們經常會使用Notification來告知用戶有新來電或新的短信。

下面先介紹一下toast的簡單提醒:

  1. private void baseToast(){
  2. Toast.makeText(getApplicationContext(), "Hello toast!", Toast.LENGTH_SHORT).show();
  3. }

第一個參數是得到上下文,第二個是提醒的具體內容,第三個是提醒的時間。


接下來看一下如何自定義一個Toast提醒:

  1. //自定義toast
  2. private void customToast(){
  3. //得到inflater對象和view
  4. LayoutInflater inflater=getLayoutInflater();
  5. View layout=inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
  6. //得到view下的相應的控件
  7. ImageView image = (ImageView) layout.findViewById(R.id.image);
  8. image.setImageResource(R.drawable.ic_launcher);
  9. TextView text = (TextView) layout.findViewById(R.id.text);
  10. text.setText("Hello! This is a custom toast!");
  11. //設置toast
  12. Toast toast=new Toast(getApplicationContext());
  13. toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
  14. toast.setDuration(Toast.LENGTH_SHORT);
  15. toast.setView(layout);
  16. toast.show();
  17. }

在layout 下定義了toast_layout.xml布局文件:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
  3. android:id="@+id/toast_layout_root"
  4. android:orientation="horizontal"
  5. android:layout_width="fill_parent"
  6. android:layout_height="fill_parent"
  7. android:padding="10dp"
  8. android:background="#DAAA"
  9. >
  10. <ImageView android:id="@+id/image"
  11. android:layout_width="wrap_content"
  12. android:layout_height="fill_parent"
  13. android:layout_marginRight="10dp"
  14. />
  15. <TextView android:id="@+id/text"
  16. android:layout_width="wrap_content"
  17. android:layout_height="fill_parent"
  18. android:textColor="#FFF"
  19. />
  20. </LinearLayout>

運行後效果:

Copyright © Linux教程網 All Rights Reserved