我的android 第三天 - 自定义Toast
16lz
2021-12-04
今天学自定义Toast。好吧,原谅我周末偷懒了!先弄2个Button。
[plain] view plain copy- <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <Button
- android:id="@+id/toast_btn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentTop="true"
- android:layout_centerHorizontal="true"
- android:layout_marginTop="17dp"
- android:text="吐司"
- android:textSize="30sp"/>
- <Button
- android:id="@+id/notice_btn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignLeft="@+id/toast_btn"
- android:layout_below="@+id/toast_btn"
- android:layout_marginTop="46dp"
- android:text="通知"/>
- </RelativeLayout>
在activity里面找到这2个Button ,添加监听
[java] view plain copy- toastBtn=(Button)findViewById(R.id.toast_btn);
- noticeBtn=(Button)findViewById(R.id.notice_btn);
- //给按钮添加监听
- toastBtn.setOnClickListener(this);
- noticeBtn.setOnClickListener(this);
判断单击了哪个View
- publicvoidonClick(Viewv){
- //判断单击了哪个View
- switch(v.getId()){
- caseR.id.toast_btn:
- //显示Toast
- toast(v);
- break;
- caseR.id.notice_btn:
- notice(v);
- }
- }
- privatevoidnotice(Viewv){
- NotificationManagermgr=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
- Notificationnotification=newNotification(R.drawable.sym_call_missed,
- "你有一个未接电话",System.currentTimeMillis());
- //意图
- Intentintent=newIntent(context,DetailActivity.class);
- //条件触发意图,转移activity
- PendingIntentpi=PendingIntent.getActivity(context,0,intent,0);
- notification.setLatestEventInfo(context,"未接电话","查看来源",pi);
- //默认提示的声音
- notification.defaults=Notification.DEFAULT_SOUND;
- //发出通知
- mgr.notify(1,notification);
- }
- privatevoidtoast(Viewv){
- Toasttoast=newToast(context);
- //设置view(就是Toast显示的界面)
- //构建一个线性布局
- LinearLayoutlayout=newLinearLayout(context);
- layout.setBackgroundResource(R.drawable.bg_yellow);
- layout.setGravity(Gravity.CENTER);
- //设置此布局为水平线性布局
- layout.setOrientation(LinearLayout.HORIZONTAL);
- //构建一个图片
- ImageViewimage=newImageView(context);
- image.setBackgroundResource(R.drawable.ic_toast);
- //添加图片到布局
- layout.addView(image);
- //构建一个文本资源
- TextViewtext=newTextView(context);
- text.setText("冰激凌");
- layout.addView(text);
- toast.setView(layout);
- //设置子控件的位置
- toast.setGravity(Gravity.CENTER,0,0);//偏移量
- //设置Toast的显示时间
- toast.setDuration(Toast.LENGTH_LONG);
- //显示吐司
- toast.show();
- }
好吧,就这样吧。。
更多相关文章
- Android(安卓)强制设置应用横屏或竖屏
- Android的设置界面及Preference使用
- TextView
- Android(安卓)剪切板操作
- Android(安卓)ImageView、TextureView、自定义View显示图片
- Android(安卓)SystemUI 信号栏后添加信号图标
- 控制软键盘显示和隐藏
- Android控件开发之四----ListView(2)
- Android(安卓)TextView 动态设置DrawableLeft