接口回调实现fragment与fragment间的跳转(含kotlin部分)

        应用场景:底部导航栏  Activity上添加四个fragment 正常情况下点击底部导航栏 实现fragment之间的跳转,底部导航栏相应的按钮的颜色改变。实际的场景是:我需要在其中一个fragment中点击按钮B,跳转到另一个fragment中,底部导航也需要相应的改变。内含kotlin的单例模式

        一、接口回调实现方法:

        1.首先在fragment中定义接口:

    /**
     * 接口
     */
    public interface goShopInterface {
        void goShop();
    }

        2.在Activity中实现接口及其方法。具体做法

    kotlin实现:   

class MainActivity : BaseActivity(), View.OnClickListener,HomeNoTabFragment.ChangeInterface, WardrobeNoStoreFragment.goShopInterface {

 //跳转到首页
    override fun goShop() {
        changeFragment(0)
        mRadioButtonHome = findViewById<RadioButton>(R.id.rb_main_home)
//        mRadioButtonSelect = findViewById<RadioButton>(R.id.rb_main_select)
        mRadioButtonHome?.isChecked = true
//        mRadioButtonSelect?.isChecked = true
        tag = 0

    }
        3.实现Activity的单例模式,调用接口的时候需要用,(不是单例会导致有的地方空指针,因为new的新对象有的地方没有初始化)

companion object {
    private var instance: MainActivity? = null
    fun instance() = instance!!
}
在onCreate中添加 instance = this 

        4.在fragment中调用接口方法

goShopInterface mgoShopInterface  = MainActivity.Companion.instance();

下面的调用

mgoShopInterface.goShop();//可以放在点击监听中

二、单选RadioButton在代码中控制颜色

kotlin代码:

mRadioButtonHome = findViewById<RadioButton>(R.id.rb_main_home)
mRadioButtonSelect = findViewById<RadioButton>(R.id.rb_main_select)
mRadioButtonHome?.isChecked = false
mRadioButtonSelect?.isChecked = true
isChecked 方法 即java中的setChecked(true)方法

    kotlin中可能因为 ?. 的原因即使空指针也没有错误

    所以

mRadioButtonHome = findViewById<RadioButton>(R.id.rb_main_home)
mRadioButtonSelect = findViewById<RadioButton>(R.id.rb_main_select)
在接口的实现方法中添加了:findViewById

    相应的文件链接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章