Android自定义视图显示和设置显示位置

1.自定义显示的视图toast_view.xml

<TextView
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content"
    android:gravity="center"
    android:layout_height="wrap_content"
    android:background="@drawable/toasts"
    android:textSize="@dimen/middle_size"
    android:textColor="@color/common_dialog_text"
    android:padding="30dip"
    android:id="@+id/toast_tv"/>

自定义TextView背景toasts.xml(圆角方框)

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <gradient
        android:angle="0"
        android:endColor="@color/operate_success_color"
        android:startColor="@color/operate_success_color"
        android:type="linear" />
    <corners android:radius="15dp" />
</shape>
 

2.工具方法显示Toast的自定义视图

/**
       * 将Toast封装在一个方法中,在其它地方使用时直接输入要弹出的内容即可
  * */
public static void ToastMessage(Activity activity, String messages) {
    //LayoutInflater的作用:对于一个没有被载入或者想要动态载入的界面,都需要LayoutInflater.inflate()来载入,LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化
    LayoutInflater inflater = activity.getLayoutInflater();//调用Activity的getLayoutInflater()
    View view = inflater.inflate(R.layout.toast_view, null); //加載layout下的布局
    TextView text = view.findViewById(R.id.toast_tv);
    text.setText(messages); //toast内容
    Toast toast = new Toast(sContext);
    toast.setGravity(Gravity.CENTER, 12, 20);//setGravity用来设置Toast显示的位置,相当于xml中的android:gravity或android:layout_gravity(通过该方法定义显示位置,自己根据需要调整就可以了)
    toast.setDuration(Toast.LENGTH_SHORT);//setDuration方法:设置持续时间,以毫秒为单位。该方法是设置补间动画时间长度的主要方法
    toast.setView(view); //添加视图文件
    toast.show();
}


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值