android ListView的数据同步刷新(ContentObserver)
以下代码是从实际项开发开代码分离出来的示例,你要明确一点,就是Service在不断的更新数据,这里只是对绑定了Adapter,并注册了ContentObserver。这里有两个同步渲染点。
- 由ContentObserver自行触发的
- 由Layout中的refresh按钮触发的
package cn.lifedu.lifebox; import cn.lifedu.lifebox.LifeboxMetaData.FeedMetaData; import android.app.Activity; import android.content.ContentResolver; import android.database.ContentObserver; import android.database.Cursor; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class FeedActivity extends Activity { private class FeedObserver extends ContentObserver { public FeedObserver(Handler handler) { super(handler); // TODO Auto-generated constructor stub } @Override public void onChange(boolean change){ super.onChange(change); if(pc.isClosed()){ return; } pc.requery(); pfa.notifyDataSetChanged(); Toast.makeText(getApplicationContext(), "observer refresh", Toast.LENGTH_LONG).show(); } } public static FeedAdapter pfa; public static Cursor pc; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.feed); TextView tv = (TextView)findViewById(R.id.textView1); tv.setText("Feed"); ListView lv = (ListView)findViewById(R.id.listView1); ContentResolver cr = getContentResolver(); Cursor c = cr.query(FeedMetaData.CONTENT_URI,null,null,null,null); FeedAdapter fa = new FeedAdapter(this,c); c.registerContentObserver(new FeedObserver(new Handler())); pfa = fa; pc = c; Button btn = (Button)findViewById(R.id.refresh); btn.setOnClickListener(new OnClickListener(){ public void onClick(View v) { // TODO Auto-generated method stub if(FeedActivity.pc.requery()){ FeedActivity.pfa.notifyDataSetChanged(); Toast.makeText(getApplicationContext(), "refresh", Toast.LENGTH_LONG).show(); }else{ Toast.makeText(getApplicationContext(), "no refresh", Toast.LENGTH_LONG).show(); } } }); lv.setAdapter(fa); } }