提问人:jo jo 提问时间:3/12/2023 最后编辑:jo jo 更新时间:3/12/2023 访问量:131
使用刀柄创建回调 - android kotlin
Create callBack with hilt - android kotlin
问:
我用刀柄写了一个回调,当我测试它只是为了调用时,它工作得很好。但是当我使用像波纹管一样时,请让我:*throw catch*
我的界面是:
interface ButtonCallback {
fun onButtonClick()
}
和模块:
@Module
@InstallIn(ActivityComponent::class)
interface ButtonCallbackModule {
@Binds
fun bindButtonCallback(activity: MainActivity): ButtonCallback
}
和 Handler:
class ButtonHandler @Inject constructor(private val callback: ButtonCallback) {
fun setButtonClickListener(imageButton: ImageButton) {
imageButton.setOnClickListener {
// Invoke the callback function
callback.onButtonClick()
}
}
}
我正在使用,就像下面一样:Activity
Fragment
@AndroidEntryPoint
class MainActivity @Inject constructor() : AppCompatActivity(), ButtonCallback {
...
override fun onButtonClick() {
when (navController.currentDestination?.id) {
R.id.navigation_lessons, R.id.navigation_lightner, R.id.navigation_quiz, R.id.navigation_profile, R.id.navigation_news -> {
if (onBackPressedDispatcher.hasEnabledCallbacks()) {
onBackPressedDispatcher.onBackPressed()
} else {
navController.navigateUp()
}
}
else -> {
navController.navigateUp()
}
}
}
...
}
和:
@AndroidEntryPoint
class NewsFragment : Fragment() {
@Inject
lateinit var buttonCallback: ButtonHandler
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
...
binding.imgBackNews.setOnClickListener {
buttonCallback.setButtonClickListener(binding.imgBackNews)
}
...
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
try {
buttonCallback =
context as ButtonHandler // callback instance
} catch (e: ClassCastException) {
throw ClassCastException("Calling Fragment must implement ButtonCallback")
}
}
我的问题在这里()我怎样才能解决这一行()来运行这些行.....onAttach
buttonCallback = context as ButtonHandler
navController.currentDestination?.id
我的就像波纹管:MainActivity
@AndroidEntryPoint
class MainActivity @Inject constructor() : AppCompatActivity(), ButtonCallback {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initNavigation()
}
private lateinit var navController: NavController
private fun initNavigation() {
val navHost =
supportFragmentManager.findFragmentById(R.id.nav_host_fragment_activity_main) as NavHostFragment
navController = navHost.navController
val navView: BottomNavigationView = binding.navViewManin
NavigationUI.setupWithNavController(navView, navController)
binding.navViewManin.setupWithNavController(navController)
binding.navViewManin.setOnNavigationItemReselectedListener {
"Reselect blocked."
}
}
override fun onButtonClick() {
when (navController.currentDestination?.id) {
R.id.navigation_lessons, R.id.navigation_lightner, R.id.navigation_quiz, R.id.navigation_profile, R.id.navigation_news -> {
if (onBackPressedDispatcher.hasEnabledCallbacks()) {
onBackPressedDispatcher.onBackPressed()
} else {
navController.navigateUp()
}
}
else -> {
navController.navigateUp()
}
}
}
}
答: 暂无答案
评论