自定义注解获取Intent传值

2021-03-25  本文已影响0人  wasdzy111
import java.lang.annotation.ElementType
import java.lang.annotation.RetentionPolicy

/**
 * 定义一个注解
 * @property value String 无值的时候,取属性名字,有值使用value的值
 * @constructor
 */
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
public annotation class AutoIntentData(val value: String = "")

import android.app.Activity
import android.os.Bundle
import android.os.Parcelable
import android.text.TextUtils
import com.google.android.material.internal.ParcelableSparseArray
import java.lang.Exception
import java.lang.RuntimeException

object AutoIntentDataUtils {
    /**
     * 方式从Intent中取值
     * @param activity Activity
     */
    fun inject(activity: Activity) {
        try {
            val intent = activity.intent
            //获取属性
            val field = activity::class.java.declaredFields
            //遍历所有属性
            field.forEach {
                it.isAccessible = true
                //获取注解
                val annotation = it.getAnnotation(AutoIntentData::class.java)
                if (null != annotation) {
                    var key = if (TextUtils.isEmpty(annotation.value)) it.name else annotation.value
                    //2、从Intent中获取
                    //判断数据类型
                    if (it.genericType.toString().equals("class java.lang.String")) {
                        if ("" != annotation.value) {
                            //根据类型冲intent中取值
                            //注解的时候设置了valute使用value的值获取
                            val valueString = intent.getStringExtra(annotation.value)
                            if (null != valueString) {
                                it.set(activity, valueString)
                            } else {
                                it.set(activity, "")
                            }
                        } else {
                            //注解的时候没有设置了valute使用属性名字获取
                            val valueString = intent.getStringExtra(it.name)
                            if (null != valueString) {
                                it.set(activity, valueString)
                            } else {
                                it.set(activity, "")
                            }
                        }
                    } else if (it.genericType.toString().equals("int") || it.genericType.toString()
                            .equals("class java.lang.Integer")
                    ) {
                        val valueString = intent.getIntExtra(key, 0)
                        it.set(activity, valueString)
                    } else if (it.genericType.toString()
                            .equals("double") || it.genericType.toString()
                            .equals("class java.lang.Double")
                    ) {
                        val valueString = intent.getDoubleExtra(key, 0.00)
                        it.set(activity, valueString)
                    } else if (it.genericType.toString()
                            .equals("boolean") || it.genericType.toString()
                            .equals("class java.lang.Boolean")
                    ) {
                        val valueString = intent.getBooleanExtra(key, false)
                        it.set(activity, valueString)
                    } else if (it.genericType.toString()
                            .equals("float") || it.genericType.toString()
                            .equals("class java.lang.Float")
                    ) {
                        val valueString = intent.getFloatExtra(key, 0F)
                        it.set(activity, valueString)
                    } else {
                        throw RuntimeException("只支持基本数据类型intent传值")
                    }
                }
            }
        } catch (e: Exception) {
            throw RuntimeException(e.message)
        }

    }

    /**
     * 从bundle中取值
     * @param activity Activity
     */
    fun injectBundle(activity: Activity) {
        try {
            val intent = activity.intent
            //1、从bunlde中获取 也可以从Intent中取值
            val extras: Bundle = intent.extras ?: return;

            //获取属性
            val field = activity::class.java.declaredFields
            //遍历所有属性
            field.forEach {
                it.isAccessible = true
                //获取注解
                val annotation = it.getAnnotation(AutoIntentData::class.java)
                if (null != annotation) {
                    val key = if (TextUtils.isEmpty(annotation.value)) it.name else annotation.value
                    if (extras.containsKey(key)) {
                        val obj = extras.get(key)
                        //需要单独处理Parcelable
                        if (obj is Parcelable) {

                        }
                        it.set(activity, obj)
                    }
                }
            }
        } catch (e: Exception) {
            throw RuntimeException(e.message)
        }

    }
}

使用

class MainActivity : AppCompatActivity() {
    var banding: ActivityMainBinding? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        banding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        banding!!.btn.setOnClickListener {
            goActivity()
        }
    }

    private fun goActivity() {
        var intent = Intent()
        intent.setClass(this, MainActivity2::class.java)
        intent.putExtra("data", "测试数据")
        intent.putExtra("data2", "你好世界")
        intent.putExtra("data3", 12)
        intent.putExtra("data4", 1.22)
        intent.putExtra("data5", true)
        var bundle = Bundle()
        bundle.putString("data6", "来之bundle")
        intent.putExtras(bundle)
        startActivity(intent)
    }
}

class MainActivity2 : AppCompatActivity() {
    @AutoIntentData(value = "data")
    public var data: String = ""

    @AutoIntentData
    public var data2: String = ""

    @AutoIntentData
    public var data3: Int = 0

    @AutoIntentData
    public var data4: Double = 0.00

    @AutoIntentData
    public var data5: Boolean = false

    @AutoIntentData
    public var data6: String = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        //初始化注解
        AutoIntentDataUtils.injectBundle(this)
//        Toast.makeText(
//            this,
//            "数据一:${data};数据二:${data2};数据三:${data3};数据四:${data4};数据五:${data5}",
//            Toast.LENGTH_LONG
//        ).show()
        Toast.makeText(
            this,
            "数据6:${data6}",
            Toast.LENGTH_LONG
        ).show()
    }
}
上一篇 下一篇

猜你喜欢

热点阅读