注意自己該編譯版本為2.3以上,預設的1.6不支援match_parent屬性,導致布局檔案出錯。 另外需要手動添加android-support-v4和otto到自己的libs檔案夾。 主要代碼邏輯: 1,在首頁面點clear按鈕,發布兩個事件並傳遞對象。 2,然後LocationHistoryFragment接收事件對象,並處理。 1,BusProvider提供一個全域唯一的Bus執行個體對象 調用的時候使用MyProvider.getBusInstance() 1 /* 2 * Copyright (C) 2012 Square, Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16 17 package com.squareup.otto.sample;18 19 import com.squareup.otto.Bus;20 21 /**22 * Maintains a singleton instance for obtaining the bus. Ideally this would be replaced with a more efficient means23 * such as through injection directly into interested classes.24 */25 public final class BusProvider {26 private static final Bus BUS = new Bus();27 28 public static Bus getInstance() {29 return BUS;30 }31 32 private BusProvider() {33 // No instances.34 }35 } 2,LocationActivity為首頁面 點擊clear按鈕會發布兩個事件對象,LocationClearEvent和LocationChangedEvent 複製代碼 findViewById(R.id.clear_location).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Tell everyone to clear their location history. //清除位置 BusProvider.getInstance().post(new LocationClearEvent()); // Post new location event for the default location. //重新載入預設的位置 lastLatitude = DEFAULT_LAT; lastLongitude = DEFAULT_LON; BusProvider.getInstance().post(produceLocationEvent()); } }); 複製代碼 1 @Override protected void onResume() { 2 super.onResume(); 3 4 // Register ourselves so that we can provide the initial value. 5 BusProvider.getInstance().register(this); 6 } 7 8 @Override protected void onPause() { 9 super.onPause();10 11 // Always unregister when an object no longer should be on the bus.12 BusProvider.getInstance().unregister(this);13 } 3,上文提到的事件發送時要傳遞的兩個對象LocationChangedEvent對象和LocationClearEvent 可以根據自己喜好,任意設定對象。代碼見demo 4,LocationHistoryFragment裡接收事件對象 同樣需要註冊和反註冊。有時我們在服務裡發布事件,則無需註冊 複製代碼 @Subscribe public void onLocationChanged(LocationChangedEvent event) { locationEvents.add(0, event.toString()); if (adapter != null) { adapter.notifyDataSetChanged(); } } @Subscribe public void onLocationCleared(LocationClearEvent event) { locationEvents.clear(); if (adapter != null) { adapter.notifyDataSetChanged(); }