问题
Background: I'm trying to implement a messenging system in my app, and I'm writing a custom CursorAdapter
to display the messages in a ListView
in the chat window. I want to use a different row layout for incoming and outgoing messages (information that is saved in the SQLite row in the cursor). Each row has the same elements in it with the same IDs, but they are arranged differently.
The Problem: Currently, I have overridden newView()
and bindView()
. When the ListView
is first populated, it creates all of the View
s perfectly, checking each row to see if it's either incoming or outgoing, and inflating the proper XML file. However, when I scroll or a new message is added to the window, the adapter recycles View
s for the wrong rows. I would override getView()
, but it is not passed the Cursor
as a parameter, so I have no way of knowing whether the row should be incoming or outgoing.
I'm not looking for code, but rather, some suggestion for an elegant implementation. Thanks in advance!
回答1:
Here are two possible solutions:
(1) Use a single layout for all items, which you can adjust when binding to show as desired. The most straight-forward way would just to have the root view be a FrameLayout which contains N children for each of the different states, and you make one of them visible and all others gone when binding. Of course you want to take care to not let this cause your items to explode in the number of views they contain.
(2) Implement Adapter.getItemViewType() http://developer.android.com/reference/android/widget/Adapter.html#getItemViewType(int) to tell the list view about the different types of items you have so it will recycle the correct one.
回答2:
Just a few thoughts, I personnaly find the whole ListView
and CursorAdapter
combination to be a little... err... is bloated the right word? Would it just be simpler to have a ScrollView
/ LinearLayout
combination that will just add the appropriate TextView
as requested?
But as for your solution, since the user seems to be unable to change the order of the messages as they are added, you could add a ArrayList<String>
field to your custom CursorAdapter
that will keep track of whether the messages are incoming or outgoing. Something like:
private ArrayList<String> cursorMonitor; //"incoming" and "outgoing" as your options.
...and then inside wherever the ListView
gets populated just use
cursorMonitor.add(my_cursor.getString("outgoing_or_incoming"));
And then in the getView()
you can override it and use the cursorMonitor
to determine which layout you need to inflate.
来源:https://stackoverflow.com/questions/6234164/how-would-i-use-a-different-row-layout-in-custom-cursoradapter-based-on-cursor-d