EventBus在Android中的簡單使用
EventBus是一個方便與Android中各組件通信的開源框架,開源地址;https://github.com/greenrobot/EventBus。EventBus功能非常強大 ,今天在做一個功能時。遇到了點擊事件的沖突問題及數據傳遞更新問題。
詳細點就是在能夠上下拉刷新的ListView的Header上有GridView。此時,GridView的OnitemClick事件與ListView的OnItemClick事件沖突。
並且我在實現 Griview的點擊事件時,還要進行數據傳遞。
解決過程1:
OnitemClick點擊沖突問題,我把在代碼中的OnitemClick事件凝視了,然後在GridView的item布局依據加了id,然後在Adapter中對整個item做了個OnClick()點擊事件,問題攻克了。
解決過程1:數據傳遞問題,就用到了EventBus:
在Activity中註冊EventBus:在Oncreate()方法中;EventBus.getDefault().register(this);
然後在OnStop()或OnDestory()中:EventBus.getDefault().unregister(this);
事件處理方法onEventMainThread:
public void onEventMainThread(CategoryItemEvent event) {
Bundle bundle = new Bundle();
bundle.putInt(...);
.......//傳遞數據,實現跳轉
在Adapter中做的就是POST事件;
holder.categoryRela.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
EventBus.getDefault().post(new CategoryItemEvent(pos));//在post的時候,傳遞了一個int類型的參數pos,這個參數在Activity中EventBus運行onEventMainThread(CategoryItemEvent event)時會用到這個pos。
}
});
EventBus在Android中的簡單使用