kotlin实现 Activity和Fragment高频代码较好的实现

Activity间的数据传递

Intent传递数据

  val intent = Intent(context, TranslucentActivity::class.java).apply {
                putExtra(Const.IntentParamsKey.OBJECT_ID, objectId)
            }
            context.startActivity(intent)

intent数据获取采用 by实现lazy加载或自定义委托实现

  private val objectId: Int by lazy {
        intent.getIntExtra(Const.IntentParamsKey.OBJECT_ID, 0)
    }

Activity传递数据到Fragment

使用Bundle传递

 companion object {

        fun newInstance(objectId: Int): SignDialogFragment {
            val fragment = SignDialogFragment()
            val args = Bundle()
            args.putInt(Const.IntentParamsKey.OBJECT_ID,objectId)
            return fragment
        }
    }
    

获取据获取采用 by实现lazy加载或自定义委托实现

  private val mObjectId: Int by lazy {
        arguments?.getInt(Const.IntentParamsKey.OBJECT_ID, 0) ?: 0
    }
    

Fragment传递数据到Activity

定义接口,在Activity实现,Fragment 转换,持有接口的引用,在需要的时候,调用回调到Activity
在onAttach进行转换

    override fun onAttach(context: Context) {
        super.onAttach(context)
        listener = context as? AddRemarkListener
        if (listener == null) {
            throw  ClassCastException("$context must implement AddRemarkInfoListener")
        }
    }

Activity于Fragment声明周期联动

按着Fragment生命周期顺序进行

  • onAttach() 与 Activity 关联时进行调用(Activity 传递到此方法内)

  • onCreateView() 调用它可创建与Fragment关联的视图层次结构

  • onActivityCreated() 当 Activity 的 onCreate() 方法已返回时进行调用

  • onStart

  • onResume

  • onPause

  • onStop

    onStart 到 onStop 之间 Activity 收到时,Activity 中的每个Fragment也会收到

  • onDestoyView 在移除与Fragment关联的视图层次结构时进行调用。

  • onDestory Activity 收到时,Activity 中的每个Fragment也会收到

  • onDetach 在取消Fragment与 Activity 的关联时进行调用。

采用顶层扩展函数抽象Fragment添加,替代查找方法

顶层函数和属性定义在kotlin文件中,和java的static修饰方法属性相当

inline fun FragmentManager.inTransaction(func: FragmentTransaction.() -> FragmentTransaction){
    beginTransaction().func().commit()
}

inline fun FragmentActivity.addFragment(fragment: Fragment, frameId: Int, tag: String){
    supportFragmentManager.inTransaction { add(frameId,fragment,tag) }
}

inline fun FragmentActivity.findFragmentByTag(tag:String): Fragment?{
    return supportFragmentManager.findFragmentByTag(tag)
}

inline fun FragmentActivity.replaceFragment(fragment: Fragment, frameId: Int){
    supportFragmentManager.inTransaction { replace(frameId,fragment) }
}

注意由于定义的是Activity的扩展属性,需要在Activity或者通过activty实例调用

在kotlin中 通过import 包+方法后直接使用了
java中调用, 需要在kotlin文件的package前通过 @file: JvmName(“KotlinUtils”) 定义java中调用的类名

看下具体代码例子
实现截图的效果kotlin实现 Activity和Fragment高频代码较好的实现_第1张图片

先进入透明的Activty,弹出DialogFragment,在DialogFragment 加载个Fragment,点击上传图片从底部弹出框

class TranslucentActivity : BaseRxActivity(), SignDialogFragment.AddRemarkListener, AttachmentListener {

    private val objectId: Int by lazy {
        intent.getIntExtra(Const.IntentParamsKey.OBJECT_ID, 0)
    }
    private var mAttachments: MutableList? = ArrayList()

    companion object {
        fun start(context: Context, objectId: Int) {
            val intent = Intent(context, TranslucentActivity::class.java).apply {
                putExtra(Const.IntentParamsKey.OBJECT_ID, objectId)
            }
            context.startActivity(intent)
        }
    }

    override fun initViews() {
        setContentView(R.layout.activity_translucent)
        addFragment(SignDialogFragment.newInstance(objectId), R.id.root_layout, "SignDialogFragment")
    }

    override fun addRemarkInfo(content: String) {

    }

    override fun uploadAttachment(attachments: MutableList?) {
        mAttachments = attachments
    }
}

class SignDialogFragment : DialogFragment() {

    private val mObjectId: Int by lazy {
        arguments?.getInt(Const.IntentParamsKey.OBJECT_ID, 0) ?: 0
    }

    private var listener: AddRemarkListener? = null
    interface AddRemarkListener {
        fun addRemarkInfo(content: String)
    }

    //fragment与activity关联时进行调用(activity 传递到此方法)
    override fun onAttach(context: Context) {
        super.onAttach(context)
        listener = context as? AddRemarkListener
        if (listener == null) {
            throw  ClassCastException("$context must implement AddRemarkInfoListener")
        }
    }

    //调用是 创建fragment的视图层次结构
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_sign_dialog, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        activity?.addFragment(VerticalImageFragment.newInstance(ArrayList(), mObjectId, ImageFragment.UPLOAD_TYPE_RICHTEXT), R.id.ll_image, "VerticalImageFragment")
        cancle.setOnClickListener {
            activity?.finish()
        }
    }

    companion object {

        fun newInstance(objectId: Int): SignDialogFragment {
            val fragment = SignDialogFragment()
            val args = Bundle()
            args.putInt(Const.IntentParamsKey.OBJECT_ID,objectId)
            return fragment
        }
    }

}

TranslucentActivity 和 SignDialogFragment 和顶层文件就包含了接本每个Activty和Fragment会碰到的代码。

VerticalImageFragment代码就省略了

你可能感兴趣的:(kotlin,android)