1 package org.hedgewars.hedgeroid.netplay; |
|
2 |
|
3 import java.util.ArrayList; |
|
4 import java.util.Collection; |
|
5 import java.util.List; |
|
6 |
|
7 import org.hedgewars.hedgeroid.netplay.MessageLog.Observer; |
|
8 |
|
9 import android.content.Context; |
|
10 import android.text.method.LinkMovementMethod; |
|
11 import android.view.View; |
|
12 import android.view.ViewGroup; |
|
13 import android.widget.AbsListView.LayoutParams; |
|
14 import android.widget.BaseAdapter; |
|
15 import android.widget.TextView; |
|
16 |
|
17 /** |
|
18 * Optimization: ListView is smart enough to try re-using the same view for an item |
|
19 * with the same ID, but it still calls getView for those items when the list changes. |
|
20 * Since lines with a given ID never change in our chatlog, we can avoid the effort |
|
21 * of TextView.setText in many cases by checking if the view is already set up for the |
|
22 * line with the right ID - but to do that, the view needs to remember the ID it's |
|
23 * holding the text for. That's what the LoglineView does. |
|
24 */ |
|
25 class LoglineView extends TextView { |
|
26 long chatlogId = -1; |
|
27 |
|
28 public LoglineView(Context context) { |
|
29 super(context); |
|
30 } |
|
31 } |
|
32 |
|
33 public class ChatlogAdapter extends BaseAdapter implements Observer { |
|
34 long idOffset = 0; |
|
35 private List<CharSequence> log = new ArrayList<CharSequence>(); |
|
36 private Context context; |
|
37 |
|
38 public ChatlogAdapter(Context context) { |
|
39 this.context = context; |
|
40 } |
|
41 |
|
42 public int getCount() { |
|
43 return log.size(); |
|
44 } |
|
45 |
|
46 public Object getItem(int position) { |
|
47 return log.get(position); |
|
48 } |
|
49 |
|
50 public long getItemId(int position) { |
|
51 return position+idOffset; |
|
52 } |
|
53 |
|
54 public boolean hasStableIds() { |
|
55 return true; |
|
56 } |
|
57 |
|
58 public void clear() { |
|
59 idOffset += log.size(); |
|
60 log.clear(); |
|
61 notifyDataSetChanged(); |
|
62 } |
|
63 |
|
64 public void lineAdded(CharSequence text) { |
|
65 log.add(text); |
|
66 notifyDataSetChanged(); |
|
67 } |
|
68 |
|
69 public void lineRemoved() { |
|
70 log.remove(0); |
|
71 idOffset += 1; |
|
72 notifyDataSetChanged(); |
|
73 } |
|
74 |
|
75 public void setLog(Collection<CharSequence> log) { |
|
76 idOffset += log.size(); |
|
77 this.log = new ArrayList<CharSequence>(log); |
|
78 notifyDataSetChanged(); |
|
79 } |
|
80 |
|
81 public View getView(int position, View convertView, ViewGroup parent) { |
|
82 LoglineView v = (LoglineView)convertView; |
|
83 if (v == null) { |
|
84 v = new LoglineView(context); |
|
85 v.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); |
|
86 v.setMovementMethod(LinkMovementMethod.getInstance()); |
|
87 } |
|
88 long id = getItemId(position); |
|
89 if(id != v.chatlogId) { |
|
90 v.setText(log.get(position)); |
|
91 v.chatlogId = id; |
|
92 } |
|
93 return v; |
|
94 } |
|
95 } |
|