扩展用户体验-Dialog,Toast,Notification

创建一个Dialog对话框

实例化一个Dialog实例,设置标题和布局,分别使用setTitle和setContentView。

例子:

// 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);

你可以用此来设置标题、消息,还可以设置按钮,选择条目,文本输入框。还能设置事件监听。

下面的例子使用AlertDialog去显示消息和2个按钮:

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 不感兴趣!

2.DatePickerDialog 选择日期用的。

3.TimePickerDialog 选择时间用的。

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);

转载于:https://my.oschina.net/wangjunhe/blog/113855

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值