本文实例讲述了Android编程实现下载时主界面与详细界面一致更新的方法。分享给大家供大家参考,具体如下:
1、创建监听管理类
public class ObserverManager { private Listobservers = new ArrayList (); public interface Observer { public void update(); public void updateState(); } public void addObserver(Observer observer) { if (observer == null) { throw new RuntimeException(); } synchronized (this) { if (!observers.contains(observer)) { observers.add(observer); } } } public void notifyObservers() { for (Observer observer : observers) { observer.update(); } } public void notifyState() { for (Observer observer : observers) { observer.updateState(); } } }
2、创建详细界面
public class DetailView extends View implements Observer { public DetailView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public DetailView(Context context, AttributeSet attrs) { super(context, attrs); } public DetailView(Context context) { super(context); } @Override public void update() { System.out.println("update"); } @Override public void updateState() { System.out.println("updateState"); } }
3、创建主界面
1)在初始化时添加监听
mObserverManager.addObserver(new DetailView(this));
2)在主界面点击下载时通知详细界面更新
public class MainActivity extends Activity { private ObserverManager mObserverManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mObserverManager = new ObserverManager(); mObserverManager.addObserver(new DetailView(this)); } public void click(View v) { //TODO 比如开始下载 mObserverManager.notifyUpdate();// } }