观察者模式其实就是 比如 给一个adapter设置了一个观察者 当adapter调用notifyDatasetchaged()方法时 会执行观察者中的回调方法
1 package com.xqx.adapterobserver; 2 3 import android.app.Activity; 4 import android.database.DataSetObserver; 5 import android.os.Bundle; 6 import android.view.View; 7 import android.widget.*; 8 import org.w3c.dom.Text; 9 10 import java.util.ArrayList; 11 import java.util.List; 12 13 public class MainActivity extends Activity { 14 /** 15 * Called when the activity is first created. 16 */ 17 18 private ArrayAdapter<Integer> adapter ; 19 private List<Integer> list; 20 private ListView listView; 21 private TextView text; 22 23 //创建观察者 24 private DataSetObserver sumObserver = new DataSetObserver() { 25 /** 26 * 当Adapter的notifyDataSetChanged方法执行时被调用 27 */ 28 @Override 29 public void onChanged() { 30 super.onChanged(); 31 //执行相应的操作 32 int sum = 0; 33 for (int i = 0; i < list.size(); i++) { 34 sum+=list.get(i); 35 } 36 text.setText("总金额:"+sum); 37 } 38 39 /** 40 * 当Adapter 调用 notifyDataSetInvalidate方法执行时被调用 41 */ 42 @Override 43 public void onInvalidated() { 44 super.onInvalidated(); 45 //执行相应的操作 46 } 47 }; 48 @Override 49 public void onCreate(Bundle savedInstanceState) { 50 super.onCreate(savedInstanceState); 51 setContentView(R.layout.main); 52 53 list = new ArrayList<Integer>(); 54 for (int i = 0; i < 30; i++) { 55 list.add(0); 56 } 57 adapter = new ArrayAdapter<Integer>(this,android.R.layout.simple_list_item_1,list); 58 //注册观察者 59 adapter.registerDataSetObserver(sumObserver); 60 text = (TextView) findViewById(R.id.text); 61 listView = (ListView) findViewById(R.id.listView); 62 listView.setAdapter(adapter); 63 64 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 65 @Override 66 public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { 67 list.set(i,2); 68 //将列表项的0变为2 更新适配器, 69 adapter.notifyDataSetChanged(); 70 //执行该方法后DataSetObserver观察者观察到 71 } 72 }); 73 74 } 75 76 @Override 77 protected void onDestroy() { 78 super.onDestroy(); 79 //注销观察者 80 adapter.unregisterDataSetObserver(sumObserver); 81 } 82 } 83 84 MainActivity.java
activity
时间: 2024-10-16 15:34:52