kotlin-android 自定义Json格式Toast

自定义Json格式Toast

第1步

首先build.gradle加入gson依赖:

 //json解析
 api 'com.google.code.gson:gson:2.8.4'

第2步

//toast_layout.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#0d1318"
android:gravity="center"
android:padding="10dp">

<TextView
    android:id="@+id/toast_message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="left"
    android:gravity="left"
    android:text=" "
    android:textColor="@color/white" />
LinearLayout>

第3步

    /**
     * 自定义Toast
     */
    @SuppressLint("SetTextI18n")
    fun showToast(context: Context, tag: String, obj: Any = "") {
        val rootView = LayoutInflater.from(context).inflate(R.layout.toast_layout, null)
        val mTextView = rootView.findViewById(R.id.toast_message) as TextView
        //判断是toast信息是obj还是String
        if (obj is String) {
            mTextView.text = "$tag: $obj"
        } else {
            val gson = GsonBuilder().setPrettyPrinting().create()
            val ss = gson.toJson(obj)
            mTextView.text = "$tag: $ss"
        }
        val toastStart = Toast(context)
        //获取屏幕高度
        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val height = wm.defaultDisplay.height
        //Y坐标偏移量设为是屏幕高度的1/3,适配所有机型
        toastStart.setGravity(Gravity.TOP, 0, height / 3)
        toastStart.duration = Toast.LENGTH_LONG
        toastStart.view = rootView
        toastStart.show()
    }

### 第4步
activity代码中调用

 //例如一个UserInfo对象,如果是obj,则调用
 showToast(application, "String", obj)
 val userInfo = intent.getSerializableExtra("selUser") as UserInfo
                    Utils.showToast(application, "收到用户身份信息", userInfo)
//例如一个String类型,则调用showToast(application, "String") ,obj可为null  
    Utils.showToast(application, "设置用户信息成功")            

### 第5步
效果图对比,自行体会:
kotlin-android 自定义Json格式Toast_第1张图片
kotlin-android 自定义Json格式Toast_第2张图片

哈哈哈哈 哈哈哈哈

你可能感兴趣的:(kotlin)