How can I make persistent changes to children in a

2019-09-18 10:27发布

问题:

So I've been trying to use an expandablelistview as an elegant interface for my application, but I continually fail to extract the needed behavior from it. When I click a child, I can change its background to a different color, or change the text to a different color, or even change the text itself. However, when I scroll around (such that the child leaves the viewable area) or collapse/expand the group, whatever change I made frequently vanishes.

So, how do I make those kind of changes to a child and get them to stick? Thanks.

UPDATE: Overriding the ExpandableListAdapter's getChildView() method to make appropriate changes to children views turns out to work just fine (even without the adapter's notifyDataSetChanged() method). My issue was a silly state switcharoo (I had them right in onChildClick but backwards in getChildView).

回答1:

The listviews on android make use of a very important technique catalyzed by convertview, when a view goes off-screen during scrolling, it is put somewhere else on screen with the data parts changed. it keeps us from making 1000 views and instead about the 7 or 8 that are on the screen at a time. but these views don't conveniently return to where you want which means that you need to specify what goes at each position, rather than letting this be happened implicitly.

so, how does that cash out? Make an arraylist or list of any kind, to hold your color states, text states w.e. and tag these with any arbitrary method (either red equals 3 in an integer arraylist or red = "red" in a string arraylist). Then it's simple, in your getView() you specify that if the corresponding position in the arraylist says something, do something. But you also need to call notifydatasetchanged() to refresh the listview. I'd suggest you put this in some onclicklistener or something because if it's without boundaries in getView(), it's gonna get called alot unnecessarily.

Next time, you show me code and i'll show you code or no one will want to help you. this gets asked alot unnecessarily.



回答2:

You need to persist the changes in the global variables in:

 public void onGroupCollapsed(int groupPosition) {
 {

and then read them back from variables and assign them to your views in

 public void onGroupExpend (int groupPosition) {
 }

or when the child is created:

public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
// assign new values / changes to your views before you return this view

return v;
}