應用場景:底部導航欄 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