问题
Assume we have an Activity
with n
TextView
s that represent one line notes. These notes are stored somewhere (local database, network etc), and each time onResume()
being called, the proper number of TextView
s are drawn according to that stored data.
Now, lets say the user want to delete a note, what would be the best way the resolve the specific TextView
, back to its storage entity?
At the moment, the only way I know is by using View.Tag
, and having some manager to translate it to data entity, but it look rather messy.
Are there any other options?
回答1:
In Android, the Adapter
acts a bridge between the view and the data model. You could display the n TextViews
in either a ListView
or a GridView
, and when the user adds or deletes a note, the local or server database is first updated. Upon completion of the web service call and/or the local database update, the new data is added to the underlying Adapter
. The View
is then refreshed by calling adapter.notifyDataSetChanged()
. This would be the way to do it.
Approaches:
- If updating the local
SQLite
database, you could consider using a CursorAdpater to hold the data for theView
, as it directly maps the entries in the local database to theView
. - If making use of a
ContentProvider
, it is even possible to combine aCursorAdapter
with a LoaderManager and a CursorLoader: these plug into theActivity
/Fragment
life-cycle and monitor the underlyingContentProvider
for changes that are published automatically to theView
on a separate thread. - It is also possible to use a
Filter
in conjunction with the
Adapter
to define a dynamic mechanism that sorts the data entries on-the-fly. The filtering is performed by theFilter
on a separate thread, as per a query entered by the user, possibly in an AutoCompleteTextView.
References:
- See the Retrieving a List of
Contacts
tutorial. The example here retrieves a set of contacts from the
contacts
ContentProvider
based on a dynamic, alphabetical search by the user. It makes use ofCursorAdapter
,CursorLoader
andLoaderManager
to monitor and update the data, and it displays the search results in aListView
. - See also the Android Realtime (Instant) Search with Filter Class example, which shows how a
Filter
is to be used. - Android AutoCompleteTextView with Custom Adapter filtering.
- Android AutocompleteTextView using ArrayAdapter and Filter.
来源:https://stackoverflow.com/questions/29456136/best-practice-for-loose-coupling-between-data-ui-in-android-adapter-filter