擴展用戶體驗-Dialog,Toast,Notification

建立一個Dialog對話框

實例化一個Dialog實例,設置標題和佈局,分別使用setTitle和setContentView。 java

例子:
android

// Create the new Dialog. 
Dialog dialog = new Dialog(MyActivity.this);

// Set the title. 
dialog.setTitle(「Dialog Title」);

// Inflate the layout. 
dialog.setContentView(R.layout.dialog_view);

// Update the Dialog’s contents. 
TextView text = (TextView)dialog.findViewById(R.id.dialog_text_view); 
text.setText(「This is the text in my dialog」); 
// Display the Dialog. 
dialog.show();

使用AlertDialog類

去構建一個AlertDialog的UI,須要建立一個新的AlertDialog.Builder對象: 數組

AlertDialog.Builder ad = new AlertDialog.Builder(context);

你能夠用此來設置標題、消息,還能夠設置按鈕,選擇條目,文本輸入框。還能設置事件監聽。 app

下面的例子使用AlertDialog去顯示消息和2個按鈕: ide

Context context = MyActivity.this; 
String title = 「It is Pitch Black」; 
String message = 「You are likely to be eaten by a Grue.」; 
String button1String = 「Go Back」; 
String button2String = 「Move Forward」;

AlertDialog.Builder ad = new AlertDialog.Builder(context); 
ad.setTitle(title); 
ad.setMessage(message);

ad.setPositiveButton( 
  button1String, 
  new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int arg1) { 
       eatenByGrue(); 
     } 
  } 
); 
ad.setNegativeButton( 
   button2String, 
   new DialogInterface.OnClickListener(){ 
     public void onClick(DialogInterface dialog, int arg1) { 
        // do nothing 
     } 
   } 
);

使用setCancelable方法去決定是否用能夠按回退按鈕關掉對話框,而不是做出一個選擇。
佈局

ad.setCancelable(true);

ad.setOnCancelListener( 
   new DialogInterface.OnCancelListener() { 
     public void onCancel(DialogInterface dialog) { 
        eatenByGrue(); 
     } 
   } 
);

幾個特殊的輸入對話款

1.CharacterPickerDialog 不感興趣! ui

2.DatePickerDialog 選擇日期用的。 this

3.TimePickerDialog 選擇時間用的。 .net

4.ProgressDialog 進度條。 線程

使用DialogFragment來管理和顯示對話框

直接看例子:

public class MyDialogFragment extends DialogFragment {

  private static String CURRENT_TIME = 「CURRENT_TIME」;

  public static MyDialogFragment newInstance(String currentTime) { 
     // Create a new Fragment instance with the specified 
     // parameters. 
     MyDialogFragment fragment = new MyDialogFragment(); 
     Bundle args = new Bundle(); 
     args.putString(CURRENT_TIME, currentTime); 
     fragment.setArguments(args);

     return fragment; 
  }

  @Override 
  public Dialog onCreateDialog(Bundle savedInstanceState) { 
     // Create the new Dialog using the AlertBuilder. 
     AlertDialog.Builder timeDialog = 
       new AlertDialog.Builder(getActivity());

     // Configure the Dialog UI. 
     timeDialog.setTitle(「The Current Time Is...」); 
     timeDialog.setMessage(getArguments().getString(CURRENT_TIME));  
     // Return the configured Dialog. 
     return timeDialog.create(); 
  } 
}

顯示一個Dialog Fragment

String tag = 「my_dialog」; 
DialogFragment myFragment = 
  MyDialogFragment.newInstance(dateString);

myFragment.show(getFragmentManager(), tag);

自定義Dialog Fragment的視圖:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
  Bundle savedInstanceState) {

  // Inflate the Dialog’s UI. 
  View view = inflater.inflate(R.layout.dialog_view, container, false);

  // Update the Dialog’s contents. 
  TextView text = (TextView)view.findViewById(R.id.dialog_text_view); 
  text.setText(「This is the text in my dialog」);

  return view; 
}

沒錯就是這個正常不過的方法。

讓Activity變成對話框

<activity android:name=」MyDialogActivity」 
             android:theme=」@android:style/Theme.Dialog」> 
</activity>

Toast

太熟悉了。小例子:

Context context = this; 
String msg = 「To health and happiness!」; 
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, msg, duration); 
toast.show();

image

自定義Toast

例子:去放置一個Toast在屏幕的底部,使用setGravity方法。

Context context = this; 
String msg = 「To the bride and groom!」; 
int duration = Toast.LENGTH_SHORT; 
Toast toast = Toast.makeText(context, msg, duration); 
int offsetX = 0; 
int offsetY = 0;

toast.setGravity(Gravity.BOTTOM, offsetX, offsetY); 
toast.show();

你能夠之定義一個View或者佈局,使用setView方法:

Context context = getApplicationContext(); 
String msg = 「Cheers!」; 
int duration = Toast.LENGTH_LONG; 
Toast toast = Toast.makeText(context, msg, duration); 
toast.setGravity(Gravity.TOP, 0, 0);

LinearLayout ll = new LinearLayout(context); 
ll.setOrientation(LinearLayout.VERTICAL);

TextView myTextView = new TextView(context); 
CompassView cv = new CompassView(context);

myTextView.setText(msg);

int lHeight = LinearLayout.LayoutParams.FILL_PARENT; 
int lWidth = LinearLayout.LayoutParams.WRAP_CONTENT;

ll.addView(cv, new LinearLayout.LayoutParams(lHeight, lWidth)); 
ll.addView(myTextView, new LinearLayout.LayoutParams(lHeight, lWidth));

ll.setPadding(40, 50, 0, 50);

toast.setView(ll); 
toast.show();

注意:Toast也認爲是UI的部分,切不要在後臺線程中直接show!!

Notification

能夠用來在狀態欄上顯示圖標和信息、使LED燈閃爍、震動手機、鈴聲或者音樂提醒、顯示額外的信息、使用可交互的控制手段。

image

介紹Notification Manager

顧名思義就是用來管理Notification,包括觸發一個新的Notification、修改存在的、取消Notifications

String svcName = Context.NOTIFICATION_SERVICE;

NotificationManager notificationManager; 
notificationManager = (NotificationManager)getSystemService(svcName);

建立一個Notification和配置在狀態欄上的顯示(因此下面說的是在狀態欄上顯示的那部分,Notification托盤在後面會說)

// Choose a drawable to display as the status bar icon 
int icon = R.drawable.icon; 
// Text to display in the status bar when the notification is launched 
String tickerText = 「Notification」; 
// The extended status bar orders notification in time order 
long when = System.currentTimeMillis();

Notification notification = new Notification(icon, tickerText, when);

ticker文本應該是做爲一個簡單的描述來通知用戶,好比短信或者email的主題等。

你能夠設置Notification對象的number屬性來顯示狀態欄上事件觸發的次數。好比:

notification.number++;

Android 3.0(API 11)引入了Notification.Builder類,所謂簡化操做用的。

最簡單的方式去給你的Notification增長聲音、燈光、震動,使用默認的設置。使用defaults屬性:

Notification.DEFAULT_LIGHTS

Notification.DEFAULT_SOUND

Notification.DEFAULT_VIBRATE

notification.defaults = Notification.DEFAULT_SOUND |
                               Notification.DEFAULT_VIBRATE;

你若想使用所有的默認值,則使用Notification.DEFAULT_ALL常量。

用鈴聲來提示

Uri ringURI =
   RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

notification.sound = ringURI;

這裏是默認的鈴聲,不過只要Uri對了,你可使用任意的鈴聲。

振動設備

振動不一樣於其餘,須要權限

<uses-permission android:name=」android.permission.VIBRATE」/>

去設置振動模式,須要有一個long[]。這個數組中的值表明時間的長度(毫秒),而後輪流下一個值表明暫停的時間。

long[] vibrate = new long[] { 1000, 1000, 1000, 1000, 1000 }; 
notification.vibrate = vibrate;

解釋下片斷代碼:振一秒停一秒,持續5秒。

閃爍LED燈

你能夠配置的有:顏色、閃爍的頻率

可是有些設備可能不支持顏色這個,可是你設置了,有就幫你顯示,木有就算了,默認唄。

ledARGB屬性用來設置顏色,ledOffMS和ledOnMS用來設置頻率和閃爍LED燈的模式。

你能夠設置ledOnMS屬性爲1,而後ledOffMS屬性爲0。或者呢,兩個屬性都爲0。

如何設置呢?

答:首先FLAG: Notification.FLAG_SHOW_LIGHTS是必須的。

notification.ledARGB = Color.RED; 
notification.ledOffMS = 0; 
notification.ledOnMS = 1; 
notification.flags = notification.flags | Notification.FLAG_SHOW_LIGHTS;

使用Notification Builder

前面已經說過,3.0引入的。

直接看例子吧,一看就懂:

Notification.Builder builder = 
   new Notification.Builder(MyActivity.this);

builder.setSmallIcon(R.drawable.ic_launcher) 
         .setTicker(「Notification」) 
         .setWhen(System.currentTimeMillis()) 
         .setDefaults(Notification.DEFAULT_SOUND | 
                          Notification.DEFAULT_VIBRATE) 
         .setSound( 
             RingtoneManager.getDefaultUri( 
               RingtoneManager.TYPE_NOTIFICATION)) 
         .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }) 
         .setLights(Color.RED, 0, 1);

Notification notification = builder.getNotification();

設置和自定義Notification托盤的UI

1.使用setLatestEventInfo方法來更新在Notification托盤上信息細節的顯示。

2.設置contentViewcontentIntent屬性來自定義UI,使用Remote View對象。(尼瑪這是什麼)

3.從3.0開始,你能夠設置Remote View中的每一個View的Broadcast Intents。

使用標準的Notification UI

最簡單的方式就是使用setLatestEventInfo方法去指定標題和文本來設置默認的Notification托盤佈局。

image

notification.setLatestEventInfo(context, 
                                         expandedTitle, 
                                         expandedText, 
                                         launchIntent);

你指定的PendingIntent ,會在用戶點擊了Notification後觸發。

Android 3.0(API level 11)拓展了每一個Notifcation的大小,支持larger icon

builder.setSmallIcon(R.drawable.ic_launcher) 
        .setTicker(「Notification」) 
        .setWhen(System.currentTimeMillis ()) 
        .setContentTitle(「Title」) 
        .setContentText(「Subtitle」) 
        .setContentInfo(「Info」) 
        .setLargeIcon(myIconBitmap) 
        .setContentIntent(pendingIntent);

別的很少說,對應着圖看吧。

image

Notification還支持裏面裝有ProgressBar:

image


builder.setSmallIcon(R.drawable.ic_launcher) 
        .setTicker(「Notification」)

.setWhen(System.currentTimeMillis()) 
.setContentTitle(「Progress」) 
.setProgress(100, 50, false) 
.setContentIntent(pendingIntent);

建立一個自定義的Notification UI

image

注意:RemoteViews中佈局的View有嚴格的限制(估計就只能有ImageView,TextView,ProgressBar)

RemoteViews myRemoteView = 
  new RemoteViews(this.getPackageName(), 
                       R.layout.my_notification_layout);

builder.setSmallIcon(R.drawable.notification_icon) 
         .setTicker(「Notification」) 
         .setWhen(System.currentTimeMillis()) 
         .setContentTitle(「Progress」) 
         .setProgress(100, 50, false) 
         .setContent(myRemoteView);

Android 3.0前,你須要:

Intent intent = new Intent(this, MyActivity.class); 
PendingIntent pendingIntent 
  = PendingIntent.getActivity(this, 0, intent, 0);

notification.contentView = new RemoteViews(this.getPackageName(), 
  R.layout.my_status_window_layout);

notification.contentIntent = pendingIntent;

注意:若是你要contentView,pendingIntent不可少,否則要報錯。

設置ContentView中的視圖

notification.contentView.setImageViewResource(R.id.status_icon, 
                                                           R.drawable.icon); 
notification.contentView.setTextViewText(R.id.status_text, 
                                                     「Current Progress:」); 
notification.contentView.setProgressBar(R.id.status_progress, 
                                                   100, 50, false);

Android 4.0(API 14)你還能夠爲ContentView中的View設置點擊事件,而後觸發一個廣播。

Intent newIntent = new Intent(BUTTON_CLICK); 
PendingIntent newPendingIntent = 
   PendingIntent.getBroadcast(MyActivity.this, 2, newIntent, 0);

notification.contentView.setOnClickPendingIntent( 
   R.id.status_progress, newPendingIntent);

自定義Ticker View

在某些設備,尤爲是平板設備,你能指定一個代替Notification Ticker文本的Remote View對象,顯示在系統欄中。

RemoteViews myTickerView = 
  new RemoteViews(this.getPackageName(), 
                      R.layout.my_ticker_layout);

builder.setSmallIcon(R.drawable.notification_icon) 
        .setTicker(「Notification」, myTickerView) 
        .setWhen(System.currentTimeMillis()) 
        .setContent(myRemoteView);

注意:ticker的文本不能省,有些設備不支持自定義ticker view>

 

配置Ongoing,Insistent的Notification

你能配置Notification爲引人注目或者不間斷的,經過設置FLAG_INSISTENTFLAG_ONGOING_EVENT標識。

Ongoing模式下的Notification,用來表明事件正在進行(好比正在下載,正在後臺播放音樂)。

Builder:

builder.setSmallIcon(R.drawable.notification_icon) 
        .setTicker(「Notification」) 
        .setWhen(System.currentTimeMillis ()) 
        .setContentTitle(「Progress」) 
        .setProgress(100, 50, false) 
        .setContent(myRemoteView) 
        .setOngoing(true);

非Builder:

notification.flags = notification.flags | 
                          Notification.FLAG_ONGOING_EVENT;

Insistent Notification 不斷重複動做:它的聲音、振動、LED光,持續着,除非被取消。

notification.flags = notification.flags | 
                           Notification.FLAG_INSISTENT;
不過這個仍是少用,會煩死人。  Builder沒有對應的設置。

觸發、更新、取消Notification

觸發一個Notification

String svc = Context.NOTIFICATION_SERVICE;

NotificationManager notificationManager 
   = (NotificationManager)getSystemService(svc);

int NOTIFICATION_REF = 1; 
Notification notification = builder.getNotification();

notificationManager.notify(NOTIFICATION_REF, notification);

這個Notification ID很重要,用來取消和更新。

更新:(若是更新不想再觸發振動、閃光之類的動做,能夠設置setOnlyAlertOnce)

builder.setSmallIcon(R.drawable.notification_icon) 
         .setTicker(「Updated Notification」) 
         .setWhen(System.currentTimeMillis ()) 
         .setContentTitle(「More Progress」) 
         .setProgress(100, 75, false)

         .setContent(myRemoteView) 
         .setOngoing(true) 
         .setOnlyAlertOnce(true);

Notification notification = builder.getNotification();

notificationManager.notify(NOTIFICATION_REF, notification);

非Buider:

notification.flags = notification.flags | 
                           Notification.FLAG_ONLY_ALERT_ONCE;

取消:(能夠設置setAutoCancel就能夠點擊後自動取消)

builder.setSmallIcon(R.drawable.ic_launcher) 
         .setTicker(「Notification」) 
         .setWhen(System.currentTimeMillis()) 
         .setContentTitle(「Title」) 
         .setContentText(「Subtitle」) 
         .setContentInfo(「Info」) 
         .setLargeIcon(myIconBitmap) 
         .setContentIntent(pendingIntent) 
         .setAutoCancel(true);

非Builder:

notification.flags = notification.flags | 
                           Notification.FLAG_AUTO_CANCEL;

直接取消能夠:

notificationManager.cancel(NOTIFICATION_REF);
相關文章
相關標籤/搜索