import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.LoaderManager; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.support.v4.widget.SimpleCursorAdapter; import android.widget.ListView; public class MainActivity extends FragmentActivity implements LoaderCallbacks<Cursor> { private ListView listview; private SimpleCursorAdapter adapter; private String uri_sms = "content://sms"; private LoaderManager loaderManager; // 這裏用的是CursorLoader,因此這裏的適配器必須用SimpleCursorAdapter,而AsyncTaskLoader兩種均可以,只是數據在後臺加載時返回值不一樣 // 並且用CursorLoader不須要和AsyncTaskLoader同樣要寫一個類來繼承AsyncTaskLoader @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listview = (ListView) this.findViewById(R.id.listView_main_titlelist); adapter = new SimpleCursorAdapter(this, R.layout.item_listview, null, new String[] { "address", "body" }, new int[] { R.id.text_item_address, R.id.text_item_body }, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); listview.setAdapter(adapter); loaderManager=getSupportLoaderManager(); loaderManager.initLoader(1, null, this); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle bundle) { // 用CursorLoader不須要和AsyncTaskLoader同樣要寫一個類來繼承AsyncTaskLoader // 直接在這裏new一個返回 return new CursorLoader(this, Uri.parse(uri_sms), null, null, null, "date desc"); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { adapter.changeCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) { adapter.changeCursor(null); } } //listview佈局 <ListView android:id="@+id/listView_main_titlelist" android:layout_width="match_parent" android:layout_height="match_parent" > </ListView> //listview中的自定義佈局 <TextView android:id="@+id/text_item_address" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" /> <TextView android:id="@+id/text_item_body" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" />