Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自定義彈出框提示效果實現代碼

編輯:關於 Android 程式設計

很多時候我們需要一個輕巧的、自動淡出的提示框來給用戶反饋信息,而不是彈出系統那種阻塞式的對話框。下面這段代碼演示如何自定義一個帶圓角、可淡入淡出的浮動提示視圖,直接上關鍵代碼。

 - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self showAlertView:@"11111"]; } //自定義彈出框 -(void)showAlertView:(NSString *)strTipText { UIView *showView=[[UIView alloc]init]; [showView setFrame:CGRectMake(100, 100, 120, 35)]; [showView setAlpha:0.0f]; [showView setBackgroundColor:[UIColor blackColor]]; [showView setClipsToBounds:YES]; [[showView layer]setMasksToBounds:YES]; [[showView layer]setCornerRadius:5.0f]; UILabel *lblTips=[[UILabel alloc]init]; [lblTips setFrame:CGRectMake(0, 0, 120, 35)]; [lblTips setText:strTipText]; [lblTips setTextAlignment:NSTextAlignmentCenter]; [lblTips setTextColor:[UIColor whiteColor]]; [lblTips setBackgroundColor:[UIColor clearColor]]; [lblTips setFont:[UIFont boldSystemFontOfSize:16]]; [showView addSubview:lblTips]; [self.view addSubview:showView]; [UIView animateWithDuration:0.5f delay:0.0f options:UIViewAnimationOptionCurveLinear animations:^{ showView.alpha=1.0f; }completion:^(BOOL finished){ [UIView animateWithDuration:1.0f delay:1.0f options:UIViewAnimationOptionCurveLinear animations:^{ showView.alpha=0.0f; }completion:^(BOOL finished){ ; }]; }]; }

這段代碼的核心思路是:先創建一個帶黑色背景與圓角的浮動視圖,初始透明度設為 0,再通過兩段動畫——先淡入顯示、停留後再淡出隱藏,實現一個優雅的臨時提示效果。需要提醒的是,此示例採用的是 iOS 的 Objective-C 寫法,Android 開發者可參考同樣的思路,用自定義 View 配合屬性動畫(如 ObjectAnimator)來實現類似的淡入淡出效果。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved