Android中自定义Toast视图和修改显示位置

来源:互联网 发布:php过滤敏感词的例子 编辑:程序博客网 时间:2024/06/06 06:41


工作笔记:项目过程中,可能会遇到需要自定义toast的视图和显示位置的需求,这里做个笔记以便日后好使用,需要的话可以直接套用;


按钮点击触发toast提示代码:

//抽取的方式可以建立一个私有的方法,把视图view 和toast文字,显示时长以及taost位置这些都提取到参数列表中

   findViewById(R.id.show_toast).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Toast toast=new Toast(MainActivity.this);                toast.setView(View.inflate(MainActivity.this,R.layout.toast,null));                ((TextView)toast.getView().findViewById(R.id.tv_toast)).setText("不可重复点赞");                toast.setGravity(Gravity.CENTER,0,0);                toast.setDuration(Toast.LENGTH_SHORT);                toast.show();//                showToast(View.inflate(MainActivity.this,R.layout.toast,null),"不可重复点赞");            }        });    private void showToast(View view,String toastMessage) {        Toast toast=new Toast(MainActivity.this);        toast.setView(view);        //这个id各位根据自己布局内的id填写        ((TextView)view.findViewById(R.id.tv_toast)).setText(toastMessage);        toast.setGravity(Gravity.CENTER,0,0);        toast.setDuration(Toast.LENGTH_SHORT);        toast.show();    }


toast的视图布局代码:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="wrap_content"    android:layout_height="wrap_content">    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/tv_toast"        android:layout_centerInParent="true"        android:background="@drawable/toast_bg"        android:textColor="@android:color/white"        /></RelativeLayout>


background背景选择器代码:

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="rectangle"    >    <solid android:color="@android:color/darker_gray" />    <corners android:radius="5dp" />    <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp"/></shape>


原创粉丝点击