我是Android新手,尝试使用EventBus将消息从Fragment发送到其容器Activity。 但是,我收到了错误:
D/EventBus: No subscribers registered for event class com.app.todo.controllers.task.TaskListFragment$TaskCreateSelectEvent
以下是与EventBus相关的Activity类中的代码:
public class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onTaskCreateSelectEvent(event: TaskListFragment.TaskCreateSelectEvent) {
Log.d("TAG", "On Main Activity")
}
fun addFragment(fragment: Fragment) {
val transaction = supportFragmentManager.beginTransaction()
transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit)
transaction.add(R.id.task_fragment_container, fragment)
transaction.addToBackStack(fragment.javaClass.simpleName)
transaction.commit()
}
public override fun onStart() {
super.onStart()
EventBus.getDefault().register(this)
}
public override fun onStop() {
super.onStop()
EventBus.getDefault().unregister(this)
}
}
以下是Fragment类
public class TaskListFragment : Fragment() {
private var fab: FloatingActionButton? = null
public class TaskCreateSelectEvent {
var fab: FloatingActionButton? = null
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
var view = inflater!!.inflate(R.layout.task_list_fragment, container, false)
fab = view.findViewById<FloatingActionButton>(R.id.fab)
fab!!.setOnClickListener {
val selectEvent = TaskCreateSelectEvent()
EventBus.getDefault().post(selectEvent)
}
return view
}
}
这是build.gradle
文件中添加库的方式。
apply plugin: 'kotlin-kapt'
dependencies {
compile 'org.greenrobot:eventbus:3.0.0'
kapt 'org.greenrobot:eventbus-annotation-processor:3.0.1' }
kapt {
arguments {
arg('eventBusIndex', 'com.app.todo.controllers.MyEventBusIndex')
}
}
知道我做错了吗?
答案 0 :(得分:1)
那么你最好熟悉匕首和rx。 事件总线在Android上是一个坏事,并且经常使事情变得更加复杂。我是Android新手......
https://www.google.de/search?q=android+rxjava+instead+of+eventbus
答案 1 :(得分:0)
尝试将您订阅的方法名称更改为:
onMessageEvent(event: TaskListFragment.TaskCreateSelectEvent)
但正如@Lord Flash建议的那样 - 使用rxjava而不是eventbus。 Tkae看看PublishSubject/PublishProcessor
(rx 2.0)类