自定义Toast
在Android中,默认的Toast样式很难看。而且,Toast存在一个小小的bug,就是后来的toast必须要等之前的toast消失后才能显现出来,不过有一个解决方案,见http://blog.csdn.net/czjuttsw/article/details/8274276
一般地,我喜欢用toast来打印一些测试信息,虽然更推荐使用LogCat。细心的人可能注意到,android的音量调节视图其实也是一个toast。
通常,我们想要显示一个toast,只需一个语句:
Toast.makeText(context,text,duration).show();
context代表上下文环境,text代表显示的内容,duration代表显示时长(Toast.LENGTH_LONG和Toast.LENGTH_SHORT)。除了这些,我们还能设置
位置(setGravity),设置View等。
下面将实现一个简单的自定义toast,喜欢的可以看一看。
主要原理是自定义View,然后调用toast.setView方法。
先看看自定义View的一个显示效果:
用到的happy pig 图片(pig.png):
-- ---------------------------------------------------------------
-- ------
-- ------
-- ---------------------------------------------------------------
步骤一:
定义一个简单的layout,命名为custom_toast.xml :
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/custom_toast_layout_id" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" android:padding="5dp" android:background="@drawable/corner" > <ImageView android:id="@+id/toastpic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/pig"/> <TextView android:id="@+id/toasttext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#000" android:paddingTop="17sp" /></LinearLayout>
步骤二:
由于自定义View的四个角是直角不好看,我们将它改变成圆角,给人感觉更加柔和。
在drawable文件夹下新建corner.xml :
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <solid android:color="#ffffffff" /> <corners android:radius="10dp" /> <padding android:bottom="5dp" android:left="5dp" android:right="5dp" android:top="5dp" /> </shape>
步骤三:
在Activity里制作一个香喷喷的toast:
public void makeCustomToast(String text,int duration) {View layout = getLayoutInflater().inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.custom_toast_layout_id)); // set a message TextView toastText = (TextView) layout.findViewById(R.id.toasttext); toastText.setText(text); // Toast... Toast toast = new Toast(this); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(duration); toast.setView(layout); toast.show();}
步骤四:
Run it!!!
参考资料来源于:
1.实现圆角:http://zcligong.blog.163.com/blog/static/210699224201293114127133/
2. 自定义Toast:http://stackoverflow.com/questions/11288475/custom-toast-in-android-a-simple-example
由于接触Android时间不是很多,难免有许多错误,望大家批评指出。
更多相关文章
- Android——TextView属性XML详解
- EditText(细节) android:maxLines="1"失效原因以及解决
- 我的Android参赛作品--此产品不代表个人
- 自定义android的tab样式
- android隐藏以及显示软键盘
- android 4.4 设置全屏
- Android(安卓)View框架总结(一)
- Android(安卓)listView 继承ListActivity的用法
- Android—TextView的XML属性和方法