1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
|
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Debug;
import android.os.Handler;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewDebug;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.KeyCharacterMap;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputConnectionWrapper;
import android.view.inputmethod.InputMethodManager;
import android.view.ContextMenu.ContextMenuInfo;
import android.gesture.GestureOverlayView;
import android.gesture.TouchThroughGestureListener;
import android.gesture.Gesture;
import android.gesture.LetterRecognizer;
import android.gesture.Prediction;
import com.android.internal.R;
import java.util.ArrayList;
import java.util.List;
/**
* Base class that can be used to implement virtualized lists of items. A list does
* not have a spatial definition here. For instance, subclases of this class can
* display the content of the list in a grid, in a carousel, as stack, etc.
*
* @attr ref android.R.styleable#AbsListView_listSelector
* @attr ref android.R.styleable#AbsListView_drawSelectorOnTop
* @attr ref android.R.styleable#AbsListView_stackFromBottom
* @attr ref android.R.styleable#AbsListView_scrollingCache
* @attr ref android.R.styleable#AbsListView_textFilterEnabled
* @attr ref android.R.styleable#AbsListView_transcriptMode
* @attr ref android.R.styleable#AbsListView_cacheColorHint
* @attr ref android.R.styleable#AbsListView_fastScrollEnabled
* @attr ref android.R.styleable#AbsListView_smoothScrollbar
* @attr ref android.R.styleable#AbsListView_gestures
*/
public abstract class AbsListView extends AdapterView<ListAdapter> implements TextWatcher,
ViewTreeObserver.OnGlobalLayoutListener, Filter.FilterListener,
ViewTreeObserver.OnTouchModeChangeListener {
/**
* Disables the transcript mode.
*
* @see #setTranscriptMode(int)
*/
public static final int TRANSCRIPT_MODE_DISABLED = 0;
/**
* The list will automatically scroll to the bottom when a data set change
* notification is received and only if the last item is already visible
* on screen.
*
* @see #setTranscriptMode(int)
*/
public static final int TRANSCRIPT_MODE_NORMAL = 1;
/**
* The list will automatically scroll to the bottom, no matter what items
* are currently visible.
*
* @see #setTranscriptMode(int)
*/
public static final int TRANSCRIPT_MODE_ALWAYS_SCROLL = 2;
/**
* Disables gestures.
*
* @see #setGestures(int)
* @see #GESTURES_JUMP
* @see #GESTURES_FILTER
*/
public static final int GESTURES_NONE = 0;
/**
* When a letter gesture is recognized the list jumps to a matching position.
*
* @see #setGestures(int)
* @see #GESTURES_NONE
* @see #GESTURES_FILTER
*/
public static final int GESTURES_JUMP = 1;
/**
* When a letter gesture is recognized the letter is added to the filter.
*
* @see #setGestures(int)
* @see #GESTURES_NONE
* @see #GESTURES_JUMP
*/
public static final int GESTURES_FILTER = 2;
/**
* Indicates that we are not in the middle of a touch gesture
*/
static final int TOUCH_MODE_REST = -1;
/**
* Indicates we just received the touch event and we are waiting to see if the it is a tap or a
* scroll gesture.
*/
static final int TOUCH_MODE_DOWN = 0;
/**
* Indicates the touch has been recognized as a tap and we are now waiting to see if the touch
* is a longpress
*/
static final int TOUCH_MODE_TAP = 1;
/**
* Indicates we have waited for everything we can wait for, but the user's finger is still down
*/
static final int TOUCH_MODE_DONE_WAITING = 2;
/**
* Indicates the touch gesture is a scroll
*/
static final int TOUCH_MODE_SCROLL = 3;
/**
* Indicates the view is in the process of being flung
*/
static final int TOUCH_MODE_FLING = 4;
/**
* Indicates that the user is currently dragging the fast scroll thumb
*/
static final int TOUCH_MODE_FAST_SCROLL = 5;
/**
* Regular layout - usually an unsolicited layout from the view system
*/
static final int LAYOUT_NORMAL = 0;
/**
* Show the first item
*/
static final int LAYOUT_FORCE_TOP = 1;
/**
* Force the selected item to be on somewhere on the screen
*/
static final int LAYOUT_SET_SELECTION = 2;
/**
* Show the last item
*/
static final int LAYOUT_FORCE_BOTTOM = 3;
/**
* Make a mSelectedItem appear in a specific location and build the rest of
* the views from there. The top is specified by mSpecificTop.
*/
static final int LAYOUT_SPECIFIC = 4;
/**
* Layout to sync as a result of a data change. Restore mSyncPosition to have its top
* at mSpecificTop
*/
static final int LAYOUT_SYNC = 5;
/**
* Layout as a result of using the navigation keys
*/
static final int LAYOUT_MOVE_SELECTION = 6;
/**
* Controls how the next layout will happen
*/
int mLayoutMode = LAYOUT_NORMAL;
/**
* Should be used by subclasses to listen to changes in the dataset
*/
AdapterDataSetObserver mDataSetObserver;
/**
* The adapter containing the data to be displayed by this view
*/
ListAdapter mAdapter;
/**
* Indicates whether the list selector should be drawn on top of the children or behind
*/
boolean mDrawSelectorOnTop = false;
/**
* The drawable used to draw the selector
*/
Drawable mSelector;
/**
* Defines the selector's location and dimension at drawing time
*/
Rect mSelectorRect = new Rect();
/**
* The data set used to store unused views that should be reused during the next layout
* to avoid creating new ones
*/
final RecycleBin mRecycler = new RecycleBin();
/**
* The selection's left padding
*/
int mSelectionLeftPadding = 0;
/**
* The selection's top padding
*/
int mSelectionTopPadding = 0;
/**
* The selection's right padding
*/
int mSelectionRightPadding = 0;
/**
* The selection's bottom padding
*/
int mSelectionBottomPadding = 0;
/**
* This view's padding
*/
Rect mListPadding = new Rect();
/**
* Subclasses must retain their measure spec from onMeasure() into this member
*/
int mWidthMeasureSpec = 0;
/**
* The top scroll indicator
*/
View mScrollUp;
/**
* The down scroll indicator
*/
View mScrollDown;
/**
* When the view is scrolling, this flag is set to true to indicate subclasses that
* the drawing cache was enabled on the children
*/
boolean mCachingStarted;
/**
* The position of the view that received the down motion event
*/
int mMotionPosition;
/**
* The offset to the top of the mMotionPosition view when the down motion event was received
*/
int mMotionViewOriginalTop;
/**
* The desired offset to the top of the mMotionPosition view after a scroll
*/
int mMotionViewNewTop;
/**
* The X value associated with the the down motion event
*/
int mMotionX;
/**
* The Y value associated with the the down motion event
*/
int mMotionY;
/**
* One of TOUCH_MODE_REST, TOUCH_MODE_DOWN, TOUCH_MODE_TAP, TOUCH_MODE_SCROLL, or
* TOUCH_MODE_DONE_WAITING
*/
int mTouchMode = TOUCH_MODE_REST;
/**
* Y value from on the previous motion event (if any)
*/
int mLastY;
/**
* How far the finger moved before we started scrolling
*/
int mMotionCorrection;
/**
* Determines speed during touch scrolling
*/
private VelocityTracker mVelocityTracker;
/**
* Handles one frame of a fling
*/
private FlingRunnable mFlingRunnable;
/**
* The offset in pixels form the top of the AdapterView to the top
* of the currently selected view. Used to save and restore state.
*/
int mSelectedTop = 0;
/**
* Indicates whether the list is stacked from the bottom edge or
* the top edge.
*/
boolean mStackFromBottom;
/**
* When set to true, the list automatically discards the children's
* bitmap cache after scrolling.
*/
boolean mScrollingCacheEnabled;
/**
* Whether or not to enable the fast scroll feature on this list
*/
boolean mFastScrollEnabled;
/**
* Optional callback to notify client when scroll position has changed
*/
private OnScrollListener mOnScrollListener;
/**
* Keeps track of our accessory window
*/
PopupWindow mPopup;
/**
* Used with type filter window
*/
EditText mTextFilter;
/**
* Indicates whether to use pixels-based or position-based scrollbar
* properties.
*/
private boolean mSmoothScrollbarEnabled = true;
/**
* Indicates that this view supports filtering
*/
private boolean mTextFilterEnabled;
/**
* Indicates that this view is currently displaying a filtered view of the data
*/
private boolean mFiltered;
/**
* Rectangle used for hit testing children
*/
private Rect mTouchFrame;
/**
* The position to resurrect the selected position to.
*/
int mResurrectToPosition = INVALID_POSITION;
private ContextMenuInfo mContextMenuInfo = null;
/**
* Used to request a layout when we changed touch mode
*/
private static final int TOUCH_MODE_UNKNOWN = -1;
private static final int TOUCH_MODE_ON = 0;
private static final int TOUCH_MODE_OFF = 1;
private int mLastTouchMode = TOUCH_MODE_UNKNOWN;
private static final boolean PROFILE_SCROLLING = false;
private boolean mScrollProfilingStarted = false;
private static final boolean PROFILE_FLINGING = false;
private boolean mFlingProfilingStarted = false;
/**
* The last CheckForLongPress runnable we posted, if any
*/
private CheckForLongPress mPendingCheckForLongPress;
/**
* The last CheckForTap runnable we posted, if any
*/
private Runnable mPendingCheckForTap;
/**
* The last CheckForKeyLongPress runnable we posted, if any
*/
private CheckForKeyLongPress mPendingCheckForKeyLongPress;
/**
* Acts upon click
*/
private AbsListView.PerformClick mPerformClick;
/**
* This view is in transcript mode -- it shows the bottom of the list when the data
* changes
*/
private int mTranscriptMode;
/**
* Indicates that this list is always drawn on top of a solid, single-color, opaque
* background
*/
private int mCacheColorHint;
/**
* The select child's view (from the adapter's getView) is enabled.
*/
private boolean mIsChildViewEnabled;
/**
* The last scroll state reported to clients through {@link OnScrollListener}.
*/
private int mLastScrollState = OnScrollListener.SCROLL_STATE_IDLE;
/**
* Helper object that renders and controls the fast scroll thumb.
*/
private FastScroller mFastScroller;
/**
* Indicates the type of gestures to use: GESTURES_NONE, GESTURES_FILTER or GESTURES_NONE
*/
private int mGestures;
// Used to implement the gestures overlay
private GestureOverlayView mGesturesOverlay;
private PopupWindow mGesturesPopup;
private ViewTreeObserver.OnGlobalLayoutListener mGesturesLayoutListener;
private boolean mGlobalLayoutListenerAddedGestures;
private boolean mInstallGesturesOverlay;
private TouchThroughGestureListener mGesturesListener;
private boolean mPreviousGesturing;
private boolean mGlobalLayoutListenerAddedFilter;
private int mTouchSlop;
private float mDensityScale;
private InputConnection mDefInputConnection;
private InputConnectionWrapper mPublicInputConnection;
private Runnable mClearScrollingCache;
/**
* Interface definition for a callback to be invoked when the list or grid
* has been scrolled.
*/
public interface OnScrollListener {
/**
* The view is not scrolling. Note navigating the list using the trackball counts as
* being in the idle state since these transitions are not animated.
*/
public static int SCROLL_STATE_IDLE = 0;
/**
* The user is scrolling using touch, and their finger is still on the screen
*/
public static int SCROLL_STATE_TOUCH_SCROLL = 1;
/**
* The user had previously been scrolling using touch and had performed a fling. The
* animation is now coasting to a stop
*/
public static int SCROLL_STATE_FLING = 2;
/**
* Callback method to be invoked while the list view or grid view is being scrolled. If the
* view is being scrolled, this method will be called before the next frame of the scroll is
* rendered. In particular, it will be called before any calls to
* {@link Adapter#getView(int, View, ViewGroup)}.
*
* @param view The view whose scroll state is being reported
*
* @param scrollState The current scroll state. One of {@link #SCROLL_STATE_IDLE},
* {@link #SCROLL_STATE_TOUCH_SCROLL} or {@link #SCROLL_STATE_IDLE}.
*/
public void onScrollStateChanged(AbsListView view, int scrollState);
/**
* Callback method to be invoked when the list or grid has been scrolled. This will be
* called after the scroll has completed
* @param view The view whose scroll state is being reported
* @param firstVisibleItem the index of the first visible cell (ignore if
* visibleItemCount == 0)
* @param visibleItemCount the number of visible cells
* @param totalItemCount the number of items in the list adaptor
*/
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount);
}
public AbsListView(Context context) {
super(context);
initAbsListView();
setVerticalScrollBarEnabled(true);
TypedArray a = context.obtainStyledAttributes(R.styleable.View);
initializeScrollbars(a);
a.recycle();
}
public AbsListView(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.absListViewStyle);
}
public AbsListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initAbsListView();
TypedArray a = context.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.AbsListView, defStyle, 0);
Drawable d = a.getDrawable(com.android.internal.R.styleable.AbsListView_listSelector);
if (d != null) {
setSelector(d);
}
mDrawSelectorOnTop = a.getBoolean(
com.android.internal.R.styleable.AbsListView_drawSelectorOnTop, false);
boolean stackFromBottom = a.getBoolean(R.styleable.AbsListView_stackFromBottom, false);
setStackFromBottom(stackFromBottom);
boolean scrollingCacheEnabled = a.getBoolean(R.styleable.AbsListView_scrollingCache, true);
setScrollingCacheEnabled(scrollingCacheEnabled);
boolean useTextFilter = a.getBoolean(R.styleable.AbsListView_textFilterEnabled, false);
setTextFilterEnabled(useTextFilter);
int transcriptMode = a.getInt(R.styleable.AbsListView_transcriptMode,
TRANSCRIPT_MODE_DISABLED);
setTranscriptMode(transcriptMode);
int color = a.getColor(R.styleable.AbsListView_cacheColorHint, 0);
setCacheColorHint(color);
boolean enableFastScroll = a.getBoolean(R.styleable.AbsListView_fastScrollEnabled, false);
setFastScrollEnabled(enableFastScroll);
boolean smoothScrollbar = a.getBoolean(R.styleable.AbsListView_smoothScrollbar, true);
setSmoothScrollbarEnabled(smoothScrollbar);
int defaultGestures = GESTURES_NONE;
if (useTextFilter) {
defaultGestures = GESTURES_FILTER;
} else if (enableFastScroll) {
defaultGestures = GESTURES_JUMP;
}
int gestures = a.getInt(R.styleable.AbsListView_gestures, defaultGestures);
setGestures(gestures);
a.recycle();
}
private void initAbsListView() {
// Setting focusable in touch mode will set the focusable property to true
setFocusableInTouchMode(true);
setWillNotDraw(false);
setAlwaysDrawnWithCacheEnabled(false);
setScrollingCacheEnabled(true);
mTouchSlop = ViewConfiguration.get(mContext).getScaledTouchSlop();
mDensityScale = getContext().getResources().getDisplayMetrics().density;
}
/**
* <p>Sets the type of gestures to use with this list. When gestures are enabled,
* that is if the <code>gestures</code> parameter is not {@link #GESTURES_NONE},
* the user can draw characters on top of this view. When a character is
* recognized and matches a known character, the list will either:</p>
* <ul>
* <li>Jump to the appropriate position ({@link #GESTURES_JUMP})</li>
* <li>Add the character to the current filter ({@link #GESTURES_FILTER})</li>
* </ul>
* <p>Using {@link #GESTURES_JUMP} requires {@link #isFastScrollEnabled()} to
* be true. Using {@link #GESTURES_FILTER} requires {@link #isTextFilterEnabled()}
* to be true.</p>
*
* @param gestures The type of gestures to enable for this list:
* {@link #GESTURES_NONE}, {@link #GESTURES_JUMP} or {@link #GESTURES_FILTER}
*
* @see #GESTURES_NONE
* @see #GESTURES_JUMP
* @see #GESTURES_FILTER
* @see #getGestures()
*/
public void setGestures(int gestures) {
switch (gestures) {
case GESTURES_JUMP:
if (!mFastScrollEnabled) {
throw new IllegalStateException("Jump gestures can only be used with "
+ "fast scroll enabled");
}
break;
case GESTURES_FILTER:
if (!mTextFilterEnabled) {
throw new IllegalStateException("Filter gestures can only be used with "
+ "text filtering enabled");
}
break;
}
final int oldGestures = mGestures;
mGestures = gestures;
// Install overlay later
if (oldGestures == GESTURES_NONE && gestures != GESTURES_NONE) {
mInstallGesturesOverlay = true;
// Uninstall overlay
} else if (oldGestures != GESTURES_NONE && gestures == GESTURES_NONE) {
uninstallGesturesOverlay();
}
}
/**
* Indicates what gestures are enabled on this view.
*
* @return {@link #GESTURES_NONE}, {@link #GESTURES_JUMP} or {@link #GESTURES_FILTER}
*
* @see #GESTURES_NONE
* @see #GESTURES_JUMP
* @see #GESTURES_FILTER
* @see #setGestures(int)
*/
@ViewDebug.ExportedProperty(mapping = {
@ViewDebug.IntToString(from = GESTURES_NONE, to = "NONE"),
@ViewDebug.IntToString(from = GESTURES_JUMP, to = "JUMP"),
@ViewDebug.IntToString(from = GESTURES_FILTER, to = "FILTER")
})
public int getGestures() {
return mGestures;
}
private void dismissGesturesPopup() {
if (mGesturesPopup != null) {
mGesturesPopup.dismiss();
}
}
private void showGesturesPopup() {
// Make sure we have a window before showing the popup
if (getWindowVisibility() == View.VISIBLE) {
installGesturesOverlay();
positionGesturesPopup();
}
}
private void positionGesturesPopup() {
final int[] xy = new int[2];
getLocationOnScreen(xy);
if (!mGesturesPopup.isShowing()) {
mGesturesPopup.showAtLocation(this, Gravity.LEFT | Gravity.TOP, xy[0], xy[1]);
} else {
mGesturesPopup.update(xy[0], xy[1], -1, -1);
}
}
private void installGesturesOverlay() {
mInstallGesturesOverlay = false;
if (mGesturesPopup == null) {
final Context c = getContext();
final LayoutInflater layoutInflater = (LayoutInflater)
c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mGesturesOverlay = (GestureOverlayView)
layoutInflater.inflate(R.layout.list_gestures_overlay, null);
final PopupWindow p = new PopupWindow(c);
p.setFocusable(false);
p.setTouchable(false);
p.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
p.setContentView(mGesturesOverlay);
p.setWidth(getWidth());
p.setHeight(getHeight());
p.setBackgroundDrawable(null);
if (mGesturesLayoutListener == null) {
mGesturesLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
if (isShown()) {
showGesturesPopup();
} else if (mGesturesPopup.isShowing()) {
dismissGesturesPopup();
}
}
};
}
getViewTreeObserver().addOnGlobalLayoutListener(mGesturesLayoutListener);
mGlobalLayoutListenerAddedGestures = true;
mGesturesPopup = p;
mGesturesOverlay.removeAllOnGestureListeners();
mGesturesListener = new TouchThroughGestureListener(null);
mGesturesListener.setGestureType(TouchThroughGestureListener.MULTIPLE_STROKE);
mGesturesListener.addOnGestureActionListener(new GesturesProcessor());
mGesturesOverlay.addOnGestureListener(mGesturesListener);
mPreviousGesturing = false;
}
}
private void uninstallGesturesOverlay() {
dismissGesturesPopup();
mGesturesPopup = null;
if (mGesturesLayoutListener != null) {
getViewTreeObserver().removeGlobalOnLayoutListener(mGesturesLayoutListener);
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mGestures != GESTURES_NONE) {
mGesturesOverlay.processEvent(ev);
final boolean isGesturing = mGesturesListener.isGesturing();
if (!isGesturing) {
mPreviousGesturing = isGesturing;
return super.dispatchTouchEvent(ev);
} else if (!mPreviousGesturing){
mPreviousGesturing = isGesturing;
final MotionEvent event = MotionEvent.obtain(ev);
event.setAction(MotionEvent.ACTION_CANCEL);
super.dispatchTouchEvent(event);
return true;
}
}
return super.dispatchTouchEvent(ev);
}
/**
* Enables fast scrolling by letting the user quickly scroll through lists by
* dragging the fast scroll thumb. The adapter attached to the list may want
* to implement {@link SectionIndexer} if it wishes to display alphabet preview and
* jump between sections of the list.
* @see SectionIndexer
* @see #isFastScrollEnabled()
* @param enabled whether or not to enable fast scrolling
*/
public void setFastScrollEnabled(boolean enabled) {
mFastScrollEnabled = enabled;
if (enabled) {
if (mFastScroller == null) {
mFastScroller = new FastScroller(getContext(), this);
}
} else {
if (mFastScroller != null) {
mFastScroller.stop();
mFastScroller = null;
}
}
}
/**
* Returns the current state of the fast scroll feature.
* @see #setFastScrollEnabled(boolean)
* @return true if fast scroll is enabled, false otherwise
*/
@ViewDebug.ExportedProperty
public boolean isFastScrollEnabled() {
return mFastScrollEnabled;
}
/**
* If fast scroll is visible, then don't draw the vertical scrollbar.
* @hide
*/
@Override
protected boolean isVerticalScrollBarHidden() {
return mFastScroller != null && mFastScroller.isVisible();
}
/**
* When smooth scrollbar is enabled, the position and size of the scrollbar thumb
* is computed based on the number of visible pixels in the visible items. This
* however assumes that all list items have the same height. If you use a list in
* which items have different heights, the scrollbar will change appearance as the
* user scrolls through the list. To avoid this issue, you need to disable this
* property.
*
* When smooth scrollbar is disabled, the position and size of the scrollbar thumb
* is based solely on the number of items in the adapter and the position of the
* visible items inside the adapter. This provides a stable scrollbar as the user
* navigates through a list of items with varying heights.
*
* @param enabled Whether or not to enable smooth scrollbar.
*
* @see #setSmoothScrollbarEnabled(boolean)
* @attr ref android.R.styleable#AbsListView_smoothScrollbar
*/
public void setSmoothScrollbarEnabled(boolean enabled) {
mSmoothScrollbarEnabled = enabled;
}
/**
* Returns the current state of the fast scroll feature.
*
* @return True if smooth scrollbar is enabled is enabled, false otherwise.
*
* @see #setSmoothScrollbarEnabled(boolean)
*/
@ViewDebug.ExportedProperty
public boolean isSmoothScrollbarEnabled() {
return mSmoothScrollbarEnabled;
}
/**
* Set the listener that will receive notifications every time the list scrolls.
*
* @param l the scroll listener
*/
public void setOnScrollListener(OnScrollListener l) {
mOnScrollListener = l;
invokeOnItemScrollListener();
}
/**
* Notify our scroll listener (if there is one) of a change in scroll state
*/
void invokeOnItemScrollListener() {
if (mFastScroller != null) {
mFastScroller.onScroll(this, mFirstPosition, getChildCount(), mItemCount);
}
if (mOnScrollListener != null) {
mOnScrollListener.onScroll(this, mFirstPosition, getChildCount(), mItemCount);
}
}
/**
* Indicates whether the children's drawing cache is used during a scroll.
* By default, the drawing cache is enabled but this will consume more memory.
*
* @return true if the scrolling cache is enabled, false otherwise
*
* @see #setScrollingCacheEnabled(boolean)
* @see View#setDrawingCacheEnabled(boolean)
*/
@ViewDebug.ExportedProperty
public boolean isScrollingCacheEnabled() {
return mScrollingCacheEnabled;
}
/**
* Enables or disables the children's drawing cache during a scroll.
* By default, the drawing cache is enabled but this will use more memory.
*
* When the scrolling cache is enabled, the caches are kept after the
* first scrolling. You can manually clear the cache by calling
* {@link android.view.ViewGroup#setChildrenDrawingCacheEnabled(boolean)}.
*
* @param enabled true to enable the scroll cache, false otherwise
*
* @see #isScrollingCacheEnabled()
* @see View#setDrawingCacheEnabled(boolean)
*/
public void setScrollingCacheEnabled(boolean enabled) {
if (mScrollingCacheEnabled && !enabled) {
clearScrollingCache();
}
mScrollingCacheEnabled = enabled;
}
/**
* Enables or disables the type filter window. If enabled, typing when
* this view has focus will filter the children to match the users input.
* Note that the {@link Adapter} used by this view must implement the
* {@link Filterable} interface.
*
* @param textFilterEnabled true to enable type filtering, false otherwise
*
* @see Filterable
*/
public void setTextFilterEnabled(boolean textFilterEnabled) {
mTextFilterEnabled = textFilterEnabled;
}
/**
* Indicates whether type filtering is enabled for this view
*
* @return true if type filtering is enabled, false otherwise
*
* @see #setTextFilterEnabled(boolean)
* @see Filterable
*/
@ViewDebug.ExportedProperty
public boolean isTextFilterEnabled() {
return mTextFilterEnabled;
}
@Override
public void getFocusedRect(Rect r) {
View view = getSelectedView();
if (view != null) {
// the focused rectangle of the selected view offset into the
// coordinate space of this view.
view.getFocusedRect(r);
offsetDescendantRectToMyCoords(view, r);
} else {
// otherwise, just the norm
super.getFocusedRect(r);
}
}
private void useDefaultSelector() {
setSelector(getResources().getDrawable(
com.android.internal.R.drawable.list_selector_background));
}
/**
* Indicates whether the content of this view is pinned to, or stacked from,
* the bottom edge.
*
* @return true if the content is stacked from the bottom edge, false otherwise
*/
@ViewDebug.ExportedProperty
public boolean isStackFromBottom() {
return mStackFromBottom;
}
/**
* When stack from bottom is set to true, the list fills its content starting from
* the bottom of the view.
*
* @param stackFromBottom true to pin the view's content to the bottom edge,
* false to pin the view's content to the top edge
*/
public void setStackFromBottom(boolean stackFromBottom) {
if (mStackFromBottom != stackFromBottom) {
mStackFromBottom = stackFromBottom;
requestLayoutIfNecessary();
}
}
void requestLayoutIfNecessary() {
if (getChildCount() > 0) {
resetList();
requestLayout();
invalidate();
}
}
static class SavedState extends BaseSavedState {
long selectedId;
long firstId;
int viewTop;
int position;
int height;
String filter;
/**
* Constructor called from {@link AbsListView#onSaveInstanceState()}
*/
SavedState(Parcelable superState) {
super(superState);
}
/**
* Constructor called from {@link #CREATOR}
*/
private SavedState(Parcel in) {
super(in);
selectedId = in.readLong();
firstId = in.readLong();
viewTop = in.readInt();
position = in.readInt();
height = in.readInt();
filter = in.readString();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeLong(selectedId);
out.writeLong(firstId);
out.writeInt(viewTop);
out.writeInt(position);
out.writeInt(height);
out.writeString(filter);
}
@Override
public String toString() {
return "AbsListView.SavedState{"
+ Integer.toHexString(System.identityHashCode(this))
+ " selectedId=" + selectedId
+ " firstId=" + firstId
+ " viewTop=" + viewTop
+ " position=" + position
+ " height=" + height
+ " filter=" + filter + "}";
}
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
@Override
public Parcelable onSaveInstanceState() {
/*
* This doesn't really make sense as the place to dismiss the
* popup, but there don't seem to be any other useful hooks
* that happen early enough to keep from getting complaints
* about having leaked the window.
*/
dismissPopup();
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
boolean haveChildren = getChildCount() > 0;
long selectedId = getSelectedItemId();
ss.selectedId = selectedId;
ss.height = getHeight();
if (selectedId >= 0) {
// Remember the selection
ss.viewTop = mSelectedTop;
ss.position = getSelectedItemPosition();
ss.firstId = INVALID_POSITION;
} else {
if (haveChildren) {
// Remember the position of the first child
View v = getChildAt(0);
ss.viewTop = v.getTop();
ss.position = mFirstPosition;
ss.firstId = mAdapter.getItemId(mFirstPosition);
} else {
ss.viewTop = 0;
ss.firstId = INVALID_POSITION;
ss.position = 0;
}
}
ss.filter = null;
if (mFiltered) {
final EditText textFilter = mTextFilter;
if (textFilter != null) {
Editable filterText = textFilter.getText();
if (filterText != null) {
ss.filter = filterText.toString();
}
}
}
return ss;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
mDataChanged = true;
mSyncHeight = ss.height;
if (ss.selectedId >= 0) {
mNeedSync = true;
mSyncRowId = ss.selectedId;
mSyncPosition = ss.position;
mSpecificTop = ss.viewTop;
mSyncMode = SYNC_SELECTED_POSITION;
} else if (ss.firstId >= 0) {
setSelectedPositionInt(INVALID_POSITION);
// Do this before setting mNeedSync since setNextSelectedPosition looks at mNeedSync
setNextSelectedPositionInt(INVALID_POSITION);
mNeedSync = true;
mSyncRowId = ss.firstId;
mSyncPosition = ss.position;
mSpecificTop = ss.viewTop;
mSyncMode = SYNC_FIRST_POSITION;
}
setFilterText(ss.filter);
requestLayout();
}
private boolean acceptFilter() {
return mTextFilterEnabled && getAdapter() instanceof Filterable &&
((Filterable) getAdapter()).getFilter() != null;
}
/**
* Sets the initial value for the text filter.
* @param filterText The text to use for the filter.
*
* @see #setTextFilterEnabled
*/
public void setFilterText(String filterText) {
// TODO: Should we check for acceptFilter()?
if (mTextFilterEnabled && !TextUtils.isEmpty(filterText)) {
createTextFilter(false);
// This is going to call our listener onTextChanged, but we might not
// be ready to bring up a window yet
mTextFilter.setText(filterText);
mTextFilter.setSelection(filterText.length());
if (mAdapter instanceof Filterable) {
// if mPopup is non-null, then onTextChanged will do the filtering
if (mPopup == null) {
Filter f = ((Filterable) mAdapter).getFilter();
f.filter(filterText);
}
// Set filtered to true so we will display the filter window when our main
// window is ready
mFiltered = true;
mDataSetObserver.clearSavedState();
}
}
}
/**
* Returns the list's text filter, if available.
* @return the list's text filter or null if filtering isn't enabled
*/
public CharSequence getTextFilter() {
if (mTextFilterEnabled && mTextFilter != null) {
return mTextFilter.getText();
}
return null;
}
@Override
protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
if (gainFocus && mSelectedPosition < 0 && !isInTouchMode()) {
resurrectSelection();
}
}
@Override
public void requestLayout() {
if (!mBlockLayoutRequests && !mInLayout) {
super.requestLayout();
}
}
/**
* The list is empty. Clear everything out.
*/
void resetList() {
removeAllViewsInLayout();
mFirstPosition = 0;
mDataChanged = false;
mNeedSync = false;
mOldSelectedPosition = INVALID_POSITION;
mOldSelectedRowId = INVALID_ROW_ID;
setSelectedPositionInt(INVALID_POSITION);
setNextSelectedPositionInt(INVALID_POSITION);
mSelectedTop = 0;
mSelectorRect.setEmpty();
invalidate();
}
@Override
protected int computeVerticalScrollExtent() {
final int count = getChildCount();
if (count > 0) {
if (mSmoothScrollbarEnabled) {
int extent = count * 100;
View view = getChildAt(0);
final int top = view.getTop();
int height = view.getHeight();
if (height > 0) {
extent += (top * 100) / height;
}
view = getChildAt(count - 1);
final int bottom = view.getBottom();
height = view.getHeight();
if (height > 0) {
extent -= ((bottom - getHeight()) * 100) / height;
}
return extent;
} else {
return 1;
}
}
return 0;
}
@Override
protected int computeVerticalScrollOffset() {
final int firstPosition = mFirstPosition;
final int childCount = getChildCount();
if (firstPosition >= 0 && childCount > 0) {
if (mSmoothScrollbarEnabled) {
final View view = getChildAt(0);
final int top = view.getTop();
int height = view.getHeight();
if (height > 0) {
return Math.max(firstPosition * 100 - (top * 100) / height, 0);
}
} else {
int index;
final int count = mItemCount;
if (firstPosition == 0) {
index = 0;
} else if (firstPosition + childCount == count) {
index = count;
} else {
index = firstPosition + childCount / 2;
}
return (int) (firstPosition + childCount * (index / (float) count));
}
}
return 0;
}
@Override
protected int computeVerticalScrollRange() {
return mSmoothScrollbarEnabled ? Math.max(mItemCount * 100, 0) : mItemCount;
}
@Override
protected float getTopFadingEdgeStrength() {
final int count = getChildCount();
final float fadeEdge = super.getTopFadingEdgeStrength();
if (count == 0) {
return fadeEdge;
} else {
if (mFirstPosition > 0) {
return 1.0f;
}
final int top = getChildAt(0).getTop();
final float fadeLength = (float) getVerticalFadingEdgeLength();
return top < mPaddingTop ? (float) -(top - mPaddingTop) / fadeLength : fadeEdge;
}
}
@Override
protected float getBottomFadingEdgeStrength() {
final int count = getChildCount();
final float fadeEdge = super.getBottomFadingEdgeStrength();
if (count == 0) {
return fadeEdge;
} else {
if (mFirstPosition + count - 1 < mItemCount - 1) {
return 1.0f;
}
final int bottom = getChildAt(count - 1).getBottom();
final int height = getHeight();
final float fadeLength = (float) getVerticalFadingEdgeLength();
return bottom > height - mPaddingBottom ?
(float) (bottom - height + mPaddingBottom) / fadeLength : fadeEdge;
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mSelector == null) {
useDefaultSelector();
}
final Rect listPadding = mListPadding;
listPadding.left = mSelectionLeftPadding + mPaddingLeft;
listPadding.top = mSelectionTopPadding + mPaddingTop;
listPadding.right = mSelectionRightPadding + mPaddingRight;
listPadding.bottom = mSelectionBottomPadding + mPaddingBottom;
}
/**
* Subclasses should NOT override this method but
* {@link #layoutChildren()} instead.
*/
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
mInLayout = true;
layoutChildren();
mInLayout = false;
}
/**
* @hide
*/
@Override
protected boolean setFrame(int left, int top, int right, int bottom) {
final boolean changed = super.setFrame(left, top, right, bottom);
if (changed) {
// Reposition the popup when the frame has changed. This includes
// translating the widget, not just changing its dimension. The
// filter popup needs to follow the widget.
final boolean visible = getWindowVisibility() == View.VISIBLE;
if (mFiltered && visible && mPopup != null && mPopup.isShowing()) {
positionPopup();
}
if (mGestures != GESTURES_NONE && visible && mGesturesPopup != null &&
mGesturesPopup.isShowing()) {
positionGesturesPopup();
}
}
return changed;
}
/**
* Subclasses must override this method to layout their children.
*/
protected void layoutChildren() {
}
void updateScrollIndicators() {
if (mScrollUp != null) {
boolean canScrollUp;
// 0th element is not visible
canScrollUp = mFirstPosition > 0;
// ... Or top of 0th element is not visible
if (!canScrollUp) {
if (getChildCount() > 0) {
View child = getChildAt(0);
canScrollUp = child.getTop() < mListPadding.top;
}
}
mScrollUp.setVisibility(canScrollUp ? View.VISIBLE : View.INVISIBLE);
}
if (mScrollDown != null) {
boolean canScrollDown;
int count = getChildCount();
// Last item is not visible
canScrollDown = (mFirstPosition + count) < mItemCount;
// ... Or bottom of the last element is not visible
if (!canScrollDown && count > 0) {
View child = getChildAt(count - 1);
canScrollDown = child.getBottom() > mBottom - mListPadding.bottom;
}
mScrollDown.setVisibility(canScrollDown ? View.VISIBLE : View.INVISIBLE);
}
}
@Override
@ViewDebug.ExportedProperty
public View getSelectedView() {
if (mItemCount > 0 && mSelectedPosition >= 0) {
return getChildAt(mSelectedPosition - mFirstPosition);
} else {
return null;
}
}
/**
* List padding is the maximum of the normal view's padding and the padding of the selector.
*
* @see android.view.View#getPaddingTop()
* @see #getSelector()
*
* @return The top list padding.
*/
public int getListPaddingTop() {
return mListPadding.top;
}
/**
* List padding is the maximum of the normal view's padding and the padding of the selector.
*
* @see android.view.View#getPaddingBottom()
* @see #getSelector()
*
* @return The bottom list padding.
*/
public int getListPaddingBottom() {
return mListPadding.bottom;
}
/**
* List padding is the maximum of the normal view's padding and the padding of the selector.
*
* @see android.view.View#getPaddingLeft()
* @see #getSelector()
*
* @return The left list padding.
*/
public int getListPaddingLeft() {
return mListPadding.left;
}
/**
* List padding is the maximum of the normal view's padding and the padding of the selector.
*
* @see android.view.View#getPaddingRight()
* @see #getSelector()
*
* @return The right list padding.
*/
public int getListPaddingRight() {
return mListPadding.right;
}
/**
* Get a view and have it show the data associated with the specified
* position. This is called when we have already discovered that the view is
* not available for reuse in the recycle bin. The only choices left are
* converting an old view or making a new one.
*
* @param position The position to display
* @return A view displaying the data associated with the specified position
*/
View obtainView(int position) {
View scrapView;
scrapView = mRecycler.getScrapView(position);
View child;
if (scrapView != null) {
if (ViewDebug.TRACE_RECYCLER) {
ViewDebug.trace(scrapView, ViewDebug.RecyclerTraceType.RECYCLE_FROM_SCRAP_HEAP,
position, -1);
}
child = mAdapter.getView(position, scrapView, this);
if (ViewDebug.TRACE_RECYCLER) {
ViewDebug.trace(child, ViewDebug.RecyclerTraceType.BIND_VIEW,
position, getChildCount());
}
if (child != scrapView) {
mRecycler.addScrapView(scrapView);
if (mCacheColorHint != 0) {
child.setDrawingCacheBackgroundColor(mCacheColorHint);
}
if (ViewDebug.TRACE_RECYCLER) {
ViewDebug.trace(scrapView, ViewDebug.RecyclerTraceType.MOVE_TO_SCRAP_HEAP,
position, -1);
}
}
} else {
child = mAdapter.getView(position, null, this);
if (mCacheColorHint != 0) {
child.setDrawingCacheBackgroundColor(mCacheColorHint);
}
if (ViewDebug.TRACE_RECYCLER) {
ViewDebug.trace(child, ViewDebug.RecyclerTraceType.NEW_VIEW,
position, getChildCount());
}
}
return child;
}
void positionSelector(View sel) {
final Rect selectorRect = mSelectorRect;
selectorRect.set(sel.getLeft(), sel.getTop(), sel.getRight(), sel.getBottom());
positionSelector(selectorRect.left, selectorRect.top, selectorRect.right,
selectorRect.bottom);
final boolean isChildViewEnabled = mIsChildViewEnabled;
if (sel.isEnabled() != isChildViewEnabled) {
mIsChildViewEnabled = !isChildViewEnabled;
refreshDrawableState();
}
}
private void positionSelector(int l, int t, int r, int b) {
mSelectorRect.set(l - mSelectionLeftPadding, t - mSelectionTopPadding, r
+ mSelectionRightPadding, b + mSelectionBottomPadding);
}
@Override
protected void dispatchDraw(Canvas canvas) {
int saveCount = 0;
final boolean clipToPadding = (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;
if (clipToPadding) {
saveCount = canvas.save();
final int scrollX = mScrollX;
final int scrollY = mScrollY;
canvas.clipRect(scrollX + mPaddingLeft, scrollY + mPaddingTop,
scrollX + mRight - mLeft - mPaddingRight,
scrollY + mBottom - mTop - mPaddingBottom);
mGroupFlags &= ~CLIP_TO_PADDING_MASK;
}
final boolean drawSelectorOnTop = mDrawSelectorOnTop;
if (!drawSelectorOnTop) {
drawSelector(canvas);
}
super.dispatchDraw(canvas);
if (drawSelectorOnTop) {
drawSelector(canvas);
}
if (clipToPadding) {
canvas.restoreToCount(saveCount);
mGroupFlags |= CLIP_TO_PADDING_MASK;
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (getChildCount() > 0) {
mDataChanged = true;
rememberSyncState();
}
if (mFastScroller != null) {
mFastScroller.onSizeChanged(w, h, oldw, oldh);
}
if (mInstallGesturesOverlay) {
installGesturesOverlay();
positionGesturesPopup();
} else if (mGesturesPopup != null) {
mGesturesPopup.update(w, h);
}
}
/**
* @return True if the current touch mode requires that we draw the selector in the pressed
* state.
*/
boolean touchModeDrawsInPressedState() {
// FIXME use isPressed for this
switch (mTouchMode) {
case TOUCH_MODE_TAP:
case TOUCH_MODE_DONE_WAITING:
return true;
default:
return false;
}
}
/**
* Indicates whether this view is in a state where the selector should be drawn. This will
* happen if we have focus but are not in touch mode, or we are in the middle of displaying
* the pressed state for an item.
*
* @return True if the selector should be shown
*/
boolean shouldShowSelector() {
return (hasFocus() && !isInTouchMode()) || touchModeDrawsInPressedState();
}
private void drawSelector(Canvas canvas) {
if (shouldShowSelector() && mSelectorRect != null && !mSelectorRect.isEmpty()) {
final Drawable selector = mSelector;
selector.setBounds(mSelectorRect);
selector.draw(canvas);
}
}
/**
* Controls whether the selection highlight drawable should be drawn on top of the item or
* behind it.
*
* @param onTop If true, the selector will be drawn on the item it is highlighting. The default
* is false.
*
* @attr ref android.R.styleable#AbsListView_drawSelectorOnTop
*/
public void setDrawSelectorOnTop(boolean onTop) {
mDrawSelectorOnTop = onTop;
}
/**
* Set a Drawable that should be used to highlight the currently selected item.
*
* @param resID A Drawable resource to use as the selection highlight.
*
* @attr ref android.R.styleable#AbsListView_listSelector
*/
public void setSelector(int resID) {
setSelector(getResources().getDrawable(resID));
}
public void setSelector(Drawable sel) {
if (mSelector != null) {
mSelector.setCallback(null);
unscheduleDrawable(mSelector);
}
mSelector = sel;
Rect padding = new Rect();
sel.getPadding(padding);
mSelectionLeftPadding = padding.left;
mSelectionTopPadding = padding.top;
mSelectionRightPadding = padding.right;
mSelectionBottomPadding = padding.bottom;
sel.setCallback(this);
sel.setState(getDrawableState());
}
/**
* Returns the selector {@link android.graphics.drawable.Drawable} that is used to draw the
* selection in the list.
*
* @return the drawable used to display the selector
*/
public Drawable getSelector() {
return mSelector;
}
/**
* Sets the selector state to "pressed" and posts a CheckForKeyLongPress to see if
* this is a long press.
*/
void keyPressed() {
Drawable selector = mSelector;
Rect selectorRect = mSelectorRect;
if (selector != null && (isFocused() || touchModeDrawsInPressedState())
&& selectorRect != null && !selectorRect.isEmpty()) {
final View v = getChildAt(mSelectedPosition - mFirstPosition);
if (v != null) {
if (v.hasFocusable()) return;
v.setPressed(true);
}
setPressed(true);
final boolean longClickable = isLongClickable();
Drawable d = selector.getCurrent();
if (d != null && d instanceof TransitionDrawable) {
if (longClickable) {
((TransitionDrawable) d).startTransition(ViewConfiguration
.getLongPressTimeout());
} else {
((TransitionDrawable) d).resetTransition();
}
}
if (longClickable && !mDataChanged) {
if (mPendingCheckForKeyLongPress == null) {
mPendingCheckForKeyLongPress = new CheckForKeyLongPress();
}
mPendingCheckForKeyLongPress.rememberWindowAttachCount();
postDelayed(mPendingCheckForKeyLongPress, ViewConfiguration.getLongPressTimeout());
}
}
}
public void setScrollIndicators(View up, View down) {
mScrollUp = up;
mScrollDown = down;
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
if (mSelector != null) {
mSelector.setState(getDrawableState());
}
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
// If the child view is enabled then do the default behavior.
if (mIsChildViewEnabled) {
// Common case
return super.onCreateDrawableState(extraSpace);
}
// The selector uses this View's drawable state. The selected child view
// is disabled, so we need to remove the enabled state from the drawable
// states.
final int enabledState = ENABLED_STATE_SET[0];
// If we don't have any extra space, it will return one of the static state arrays,
// and clearing the enabled state on those arrays is a bad thing! If we specify
// we need extra space, it will create+copy into a new array that safely mutable.
int[] state = super.onCreateDrawableState(extraSpace + 1);
int enabledPos = -1;
for (int i = state.length - 1; i >= 0; i--) {
if (state[i] == enabledState) {
enabledPos = i;
break;
}
}
// Remove the enabled state
if (enabledPos >= 0) {
System.arraycopy(state, enabledPos + 1, state, enabledPos,
state.length - enabledPos - 1);
}
return state;
}
@Override
public boolean verifyDrawable(Drawable dr) {
return mSelector == dr || super.verifyDrawable(dr);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
final ViewTreeObserver treeObserver = getViewTreeObserver();
if (treeObserver != null) {
treeObserver.addOnTouchModeChangeListener(this);
if (mTextFilterEnabled && mPopup != null && !mGlobalLayoutListenerAddedFilter) {
treeObserver.addOnGlobalLayoutListener(this);
}
if (mGestures != GESTURES_NONE && mGesturesPopup != null &&
!mGlobalLayoutListenerAddedGestures) {
treeObserver.addOnGlobalLayoutListener(mGesturesLayoutListener);
}
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
final ViewTreeObserver treeObserver = getViewTreeObserver();
if (treeObserver != null) {
treeObserver.removeOnTouchModeChangeListener(this);
if (mTextFilterEnabled && mPopup != null) {
treeObserver.removeGlobalOnLayoutListener(this);
mGlobalLayoutListenerAddedFilter = false;
}
if (mGesturesLayoutListener != null && mGesturesPopup != null) {
mGlobalLayoutListenerAddedGestures = false;
treeObserver.removeGlobalOnLayoutListener(mGesturesLayoutListener);
}
}
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
final int touchMode = isInTouchMode() ? TOUCH_MODE_ON : TOUCH_MODE_OFF;
if (!hasWindowFocus) {
setChildrenDrawingCacheEnabled(false);
removeCallbacks(mFlingRunnable);
// Always hide the type filter
dismissPopup();
dismissGesturesPopup();
if (touchMode == TOUCH_MODE_OFF) {
// Remember the last selected element
mResurrectToPosition = mSelectedPosition;
}
} else {
if (mFiltered) {
// Show the type filter only if a filter is in effect
showPopup();
}
if (mGestures != GESTURES_NONE) {
showGesturesPopup();
}
// If we changed touch mode since the last time we had focus
if (touchMode != mLastTouchMode && mLastTouchMode != TOUCH_MODE_UNKNOWN) {
// If we come back in trackball mode, we bring the selection back
if (touchMode == TOUCH_MODE_OFF) {
// This will trigger a layout
resurrectSelection();
// If we come back in touch mode, then we want to hide the selector
} else {
hideSelector();
mLayoutMode = LAYOUT_NORMAL;
layoutChildren();
}
}
}
mLastTouchMode = touchMode;
}
/**
* Creates the ContextMenuInfo returned from {@link #getContextMenuInfo()}. This
* methods knows the view, position and ID of the item that received the
* long press.
*
* @param view The view that received the long press.
* @param position The position of the item that received the long press.
* @param id The ID of the item that received the long press.
* @return The extra information that should be returned by
* {@link #getContextMenuInfo()}.
*/
ContextMenuInfo createContextMenuInfo(View view, int position, long id) {
return new AdapterContextMenuInfo(view, position, id);
}
/**
* A base class for Runnables that will check that their view is still attached to
* the original window as when the Runnable was created.
*
*/
private class WindowRunnnable {
private int mOriginalAttachCount;
public void rememberWindowAttachCount() {
mOriginalAttachCount = getWindowAttachCount();
}
public boolean sameWindow() {
return hasWindowFocus() && getWindowAttachCount() == mOriginalAttachCount;
}
}
private class PerformClick extends WindowRunnnable implements Runnable {
View mChild;
int mClickMotionPosition;
public void run() {
// The data has changed since we posted this action in the event queue,
// bail out before bad things happen
if (mDataChanged) return;
if (mAdapter != null && mItemCount > 0 &&
mClickMotionPosition < mAdapter.getCount() && sameWindow()) {
performItemClick(mChild, mClickMotionPosition, getAdapter().getItemId(
mClickMotionPosition));
}
}
}
private class CheckForLongPress extends WindowRunnnable implements Runnable {
public void run() {
final int motionPosition = mMotionPosition;
final View child = getChildAt(motionPosition - mFirstPosition);
if (child != null) {
final int longPressPosition = mMotionPosition;
final long longPressId = mAdapter.getItemId(mMotionPosition);
boolean handled = false;
if (sameWindow() && !mDataChanged) {
handled = performLongPress(child, longPressPosition, longPressId);
}
if (handled) {
mTouchMode = TOUCH_MODE_REST;
setPressed(false);
child.setPressed(false);
} else {
mTouchMode = TOUCH_MODE_DONE_WAITING;
}
}
}
}
private class CheckForKeyLongPress extends WindowRunnnable implements Runnable {
public void run() {
if (isPressed() && mSelectedPosition >= 0) {
int index = mSelectedPosition - mFirstPosition;
View v = getChildAt(index);
if (!mDataChanged) {
boolean handled = false;
if (sameWindow()) {
handled = performLongPress(v, mSelectedPosition, mSelectedRowId);
}
if (handled) {
setPressed(false);
v.setPressed(false);
}
} else {
setPressed(false);
if (v != null) v.setPressed(false);
}
}
}
}
private boolean performLongPress(final View child,
final int longPressPosition, final long longPressId) {
boolean handled = false;
if (mOnItemLongClickListener != null) {
handled = mOnItemLongClickListener.onItemLongClick(AbsListView.this, child,
longPressPosition, longPressId);
}
if (!handled) {
mContextMenuInfo = createContextMenuInfo(child, longPressPosition, longPressId);
handled = super.showContextMenuForChild(AbsListView.this);
}
if (handled) {
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
}
return handled;
}
@Override
protected ContextMenuInfo getContextMenuInfo() {
return mContextMenuInfo;
}
@Override
public boolean showContextMenuForChild(View originalView) {
final int longPressPosition = getPositionForView(originalView);
if (longPressPosition >= 0) {
final long longPressId = mAdapter.getItemId(longPressPosition);
boolean handled = false;
if (mOnItemLongClickListener != null) {
handled = mOnItemLongClickListener.onItemLongClick(AbsListView.this, originalView,
longPressPosition, longPressId);
}
if (!handled) {
mContextMenuInfo = createContextMenuInfo(
getChildAt(longPressPosition - mFirstPosition),
longPressPosition, longPressId);
handled = super.showContextMenuForChild(originalView);
}
return handled;
}
return false;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
if (isPressed() && mSelectedPosition >= 0 && mAdapter != null &&
mSelectedPosition < mAdapter.getCount()) {
final View view = getChildAt(mSelectedPosition - mFirstPosition);
performItemClick(view, mSelectedPosition, mSelectedRowId);
setPressed(false);
if (view != null) view.setPressed(false);
return true;
}
}
return super.onKeyUp(keyCode, event);
}
@Override
protected void dispatchSetPressed(boolean pressed) {
// Don't dispatch setPressed to our children. We call setPressed on ourselves to
// get the selector in the right state, but we don't want to press each child.
}
/**
* Maps a point to a position in the list.
*
* @param x X in local coordinate
* @param y Y in local coordinate
* @return The position of the item which contains the specified point, or
* {@link #INVALID_POSITION} if the point does not intersect an item.
*/
public int pointToPosition(int x, int y) {
Rect frame = mTouchFrame;
if (frame == null) {
mTouchFrame = new Rect();
frame = mTouchFrame;
}
final int count = getChildCount();
for (int i = count - 1; i >= 0; i--) {
final View child = getChildAt(i);
if (child.getVisibility() == View.VISIBLE) {
child.getHitRect(frame);
if (frame.contains(x, y)) {
return mFirstPosition + i;
}
}
}
return INVALID_POSITION;
}
/**
* Maps a point to a the rowId of the item which intersects that point.
*
* @param x X in local coordinate
* @param y Y in local coordinate
* @return The rowId of the item which contains the specified point, or {@link #INVALID_ROW_ID}
* if the point does not intersect an item.
*/
public long pointToRowId(int x, int y) {
int position = pointToPosition(x, y);
if (position >= 0) {
return mAdapter.getItemId(position);
}
return INVALID_ROW_ID;
}
final class CheckForTap implements Runnable {
public void run() {
if (mTouchMode == TOUCH_MODE_DOWN) {
mTouchMode = TOUCH_MODE_TAP;
final View child = getChildAt(mMotionPosition - mFirstPosition);
if (child != null && !child.hasFocusable()) {
mLayoutMode = LAYOUT_NORMAL;
if (!mDataChanged) {
layoutChildren();
child.setPressed(true);
positionSelector(child);
setPressed(true);
final int longPressTimeout = ViewConfiguration.getLongPressTimeout();
final boolean longClickable = isLongClickable();
if (mSelector != null) {
Drawable d = mSelector.getCurrent();
if (d != null && d instanceof TransitionDrawable) {
if (longClickable) {
((TransitionDrawable) d).startTransition(longPressTimeout);
} else {
((TransitionDrawable) d).resetTransition();
}
}
}
if (longClickable) {
if (mPendingCheckForLongPress == null) {
mPendingCheckForLongPress = new CheckForLongPress();
}
mPendingCheckForLongPress.rememberWindowAttachCount();
postDelayed(mPendingCheckForLongPress, longPressTimeout);
} else {
mTouchMode = TOUCH_MODE_DONE_WAITING;
}
} else {
mTouchMode = TOUCH_MODE_DONE_WAITING;
}
}
}
}
}
private boolean startScrollIfNeeded(int deltaY) {
// Check if we have moved far enough that it looks more like a
// scroll than a tap
final int distance = Math.abs(deltaY);
if (distance > mTouchSlop) {
createScrollingCache();
mTouchMode = TOUCH_MODE_SCROLL;
mMotionCorrection = deltaY;
final Handler handler = getHandler();
// Handler should not be null unless the AbsListView is not attached to a
// window, which would make it very hard to scroll it... but the monkeys
// say it's possible.
if (handler != null) {
handler.removeCallbacks(mPendingCheckForLongPress);
}
setPressed(false);
View motionView = getChildAt(mMotionPosition - mFirstPosition);
if (motionView != null) {
motionView.setPressed(false);
}
reportScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
// Time to start stealing events! Once we've stolen them, don't let anyone
// steal from us
requestDisallowInterceptTouchEvent(true);
return true;
}
return false;
}
public void onTouchModeChanged(boolean isInTouchMode) {
if (isInTouchMode) {
// Get rid of the selection when we enter touch mode
hideSelector();
// Layout, but only if we already have done so previously.
// (Otherwise may clobber a LAYOUT_SYNC layout that was requested to restore
// state.)
if (getHeight() > 0 && getChildCount() > 0) {
// We do not lose focus initiating a touch (since AbsListView is focusable in
// touch mode). Force an initial layout to get rid of the selection.
mLayoutMode = LAYOUT_NORMAL;
layoutChildren();
}
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mFastScroller != null) {
boolean intercepted = mFastScroller.onTouchEvent(ev);
if (intercepted) {
return true;
}
}
final int action = ev.getAction();
final int x = (int) ev.getX();
final int y = (int) ev.getY();
View v;
int deltaY;
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
switch (action) {
case MotionEvent.ACTION_DOWN: {
int motionPosition = pointToPosition(x, y);
if (!mDataChanged) {
if ((mTouchMode != TOUCH_MODE_FLING) && (motionPosition >= 0)
&& (getAdapter().isEnabled(motionPosition))) {
// User clicked on an actual view (and was not stopping a fling). It might be a
// click or a scroll. Assume it is a click until proven otherwise
mTouchMode = TOUCH_MODE_DOWN;
// FIXME Debounce
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
if (ev.getEdgeFlags() != 0 && motionPosition < 0) {
// If we couldn't find a view to click on, but the down event was touching
// the edge, we will bail out and try again. This allows the edge correcting
// code in ViewRoot to try to find a nearby view to select
return false;
}
// User clicked on whitespace, or stopped a fling. It is a scroll.
createScrollingCache();
mTouchMode = TOUCH_MODE_SCROLL;
mMotionCorrection = 0;
motionPosition = findMotionRow(y);
reportScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
}
}
if (motionPosition >= 0) {
// Remember where the motion event started
v = getChildAt(motionPosition - mFirstPosition);
mMotionViewOriginalTop = v.getTop();
mMotionX = x;
mMotionY = y;
mMotionPosition = motionPosition;
}
mLastY = Integer.MIN_VALUE;
break;
}
case MotionEvent.ACTION_MOVE: {
deltaY = y - mMotionY;
switch (mTouchMode) {
case TOUCH_MODE_DOWN:
case TOUCH_MODE_TAP:
case TOUCH_MODE_DONE_WAITING:
// Check if we have moved far enough that it looks more like a
// scroll than a tap
startScrollIfNeeded(deltaY);
break;
case TOUCH_MODE_SCROLL:
if (PROFILE_SCROLLING) {
if (!mScrollProfilingStarted) {
Debug.startMethodTracing("AbsListViewScroll");
mScrollProfilingStarted = true;
}
}
if (y != mLastY) {
deltaY -= mMotionCorrection;
int incrementalDeltaY = mLastY != Integer.MIN_VALUE ? y - mLastY : deltaY;
trackMotionScroll(deltaY, incrementalDeltaY);
// Check to see if we have bumped into the scroll limit
View motionView = this.getChildAt(mMotionPosition - mFirstPosition);
if (motionView != null) {
// Check if the top of the motion view is where it is
// supposed to be
if (motionView.getTop() != mMotionViewNewTop) {
// We did not scroll the full amount. Treat this essentially like the
// start of a new touch scroll
final int motionPosition = findMotionRow(y);
mMotionCorrection = 0;
motionView = getChildAt(motionPosition - mFirstPosition);
mMotionViewOriginalTop = motionView.getTop();
mMotionY = y;
mMotionPosition = motionPosition;
}
}
mLastY = y;
}
break;
}
break;
}
case MotionEvent.ACTION_UP: {
switch (mTouchMode) {
case TOUCH_MODE_DOWN:
case TOUCH_MODE_TAP:
case TOUCH_MODE_DONE_WAITING:
final int motionPosition = mMotionPosition;
final View child = getChildAt(motionPosition - mFirstPosition);
if (child != null && !child.hasFocusable()) {
if (mTouchMode != TOUCH_MODE_DOWN) {
child.setPressed(false);
}
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
final AbsListView.PerformClick performClick = mPerformClick;
performClick.mChild = child;
performClick.mClickMotionPosition = motionPosition;
performClick.rememberWindowAttachCount();
mResurrectToPosition = motionPosition;
if (mTouchMode == TOUCH_MODE_DOWN || mTouchMode == TOUCH_MODE_TAP) {
final Handler handler = getHandler();
if (handler != null) {
handler.removeCallbacks(mTouchMode == TOUCH_MODE_DOWN ?
mPendingCheckForTap : mPendingCheckForLongPress);
}
mLayoutMode = LAYOUT_NORMAL;
mTouchMode = TOUCH_MODE_TAP;
if (!mDataChanged) {
setSelectedPositionInt(mMotionPosition);
layoutChildren();
child.setPressed(true);
positionSelector(child);
setPressed(true);
if (mSelector != null) {
Drawable d = mSelector.getCurrent();
if (d != null && d instanceof TransitionDrawable) {
((TransitionDrawable)d).resetTransition();
}
}
postDelayed(new Runnable() {
public void run() {
child.setPressed(false);
setPressed(false);
if (!mDataChanged) {
post(performClick);
}
mTouchMode = TOUCH_MODE_REST;
}
}, ViewConfiguration.getPressedStateDuration());
}
return true;
} else {
if (!mDataChanged) {
post(performClick);
}
}
}
mTouchMode = TOUCH_MODE_REST;
break;
case TOUCH_MODE_SCROLL:
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000);
int initialVelocity = (int)velocityTracker.getYVelocity();
if ((Math.abs(initialVelocity) >
ViewConfiguration.get(mContext).getScaledMinimumFlingVelocity()) &&
(getChildCount() > 0)) {
if (mFlingRunnable == null) {
mFlingRunnable = new FlingRunnable();
}
reportScrollStateChange(OnScrollListener.SCROLL_STATE_FLING);
mFlingRunnable.start(-initialVelocity);
} else {
mTouchMode = TOUCH_MODE_REST;
reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
}
}
setPressed(false);
// Need to redraw since we probably aren't drawing the selector anymore
invalidate();
final Handler handler = getHandler();
if (handler != null) {
handler.removeCallbacks(mPendingCheckForLongPress);
}
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
if (PROFILE_SCROLLING) {
if (mScrollProfilingStarted) {
Debug.stopMethodTracing();
mScrollProfilingStarted = false;
}
}
break;
}
case MotionEvent.ACTION_CANCEL: {
mTouchMode = TOUCH_MODE_REST;
setPressed(false);
View motionView = this.getChildAt(mMotionPosition - mFirstPosition);
if (motionView != null) {
motionView.setPressed(false);
}
clearScrollingCache();
final Handler handler = getHandler();
if (handler != null) {
handler.removeCallbacks(mPendingCheckForLongPress);
}
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
}
return true;
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (mFastScroller != null) {
mFastScroller.draw(canvas);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
int action = ev.getAction();
int x = (int) ev.getX();
int y = (int) ev.getY();
View v;
if (mFastScroller != null) {
boolean intercepted = mFastScroller.onInterceptTouchEvent(ev);
if (intercepted) {
return true;
}
}
switch (action) {
case MotionEvent.ACTION_DOWN: {
int motionPosition = findMotionRow(y);
if (mTouchMode != TOUCH_MODE_FLING && motionPosition >= 0) {
// User clicked on an actual view (and was not stopping a fling).
// Remember where the motion event started
v = getChildAt(motionPosition - mFirstPosition);
mMotionViewOriginalTop = v.getTop();
mMotionX = x;
mMotionY = y;
mMotionPosition = motionPosition;
mTouchMode = TOUCH_MODE_DOWN;
clearScrollingCache();
}
mLastY = Integer.MIN_VALUE;
break;
}
case MotionEvent.ACTION_MOVE: {
switch (mTouchMode) {
case TOUCH_MODE_DOWN:
if (startScrollIfNeeded(y - mMotionY)) {
return true;
}
break;
}
break;
}
case MotionEvent.ACTION_UP: {
mTouchMode = TOUCH_MODE_REST;
reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
break;
}
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public void addTouchables(ArrayList<View> views) {
final int count = getChildCount();
final int firstPosition = mFirstPosition;
final ListAdapter adapter = mAdapter;
if (adapter == null) {
return;
}
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (adapter.isEnabled(firstPosition + i)) {
views.add(child);
}
child.addTouchables(views);
}
}
/**
* Fires an "on scroll state changed" event to the registered
* {@link android.widget.AbsListView.OnScrollListener}, if any. The state change
* is fired only if the specified state is different from the previously known state.
*
* @param newState The new scroll state.
*/
void reportScrollStateChange(int newState) {
if (newState != mLastScrollState) {
if (mOnScrollListener != null) {
mOnScrollListener.onScrollStateChanged(this, newState);
mLastScrollState = newState;
}
}
}
/**
* Responsible for fling behavior. Use {@link #start(int)} to
* initiate a fling. Each frame of the fling is handled in {@link #run()}.
* A FlingRunnable will keep re-posting itself until the fling is done.
*
*/
private class FlingRunnable implements Runnable {
/**
* Tracks the decay of a fling scroll
*/
private Scroller mScroller;
/**
* Y value reported by mScroller on the previous fling
*/
private int mLastFlingY;
public FlingRunnable() {
mScroller = new Scroller(getContext());
}
public void start(int initialVelocity) {
int initialY = initialVelocity < 0 ? Integer.MAX_VALUE : 0;
mLastFlingY = initialY;
mScroller.fling(0, initialY, 0, initialVelocity,
0, Integer.MAX_VALUE, 0, Integer.MAX_VALUE);
mTouchMode = TOUCH_MODE_FLING;
post(this);
if (PROFILE_FLINGING) {
if (!mFlingProfilingStarted) {
Debug.startMethodTracing("AbsListViewFling");
mFlingProfilingStarted = true;
}
}
}
private void endFling() {
mTouchMode = TOUCH_MODE_REST;
reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
clearScrollingCache();
}
public void run() {
if (mTouchMode != TOUCH_MODE_FLING) {
return;
}
if (mItemCount == 0 || getChildCount() == 0) {
endFling();
return;
}
final Scroller scroller = mScroller;
boolean more = scroller.computeScrollOffset();
final int y = scroller.getCurrY();
// Flip sign to convert finger direction to list items direction
// (e.g. finger moving down means list is moving towards the top)
int delta = mLastFlingY - y;
// Pretend that each frame of a fling scroll is a touch scroll
if (delta > 0) {
// List is moving towards the top. Use first view as mMotionPosition
mMotionPosition = mFirstPosition;
final View firstView = getChildAt(0);
mMotionViewOriginalTop = firstView.getTop();
// Don't fling more than 1 screen
delta = Math.min(getHeight() - mPaddingBottom - mPaddingTop - 1, delta);
} else {
// List is moving towards the bottom. Use last view as mMotionPosition
int offsetToLast = getChildCount() - 1;
mMotionPosition = mFirstPosition + offsetToLast;
final View lastView = getChildAt(offsetToLast);
mMotionViewOriginalTop = lastView.getTop();
// Don't fling more than 1 screen
delta = Math.max(-(getHeight() - mPaddingBottom - mPaddingTop - 1), delta);
}
trackMotionScroll(delta, delta);
// Check to see if we have bumped into the scroll limit
View motionView = getChildAt(mMotionPosition - mFirstPosition);
if (motionView != null) {
// Check if the top of the motion view is where it is
// supposed to be
if (motionView.getTop() != mMotionViewNewTop) {
more = false;
}
}
if (more) {
invalidate();
mLastFlingY = y;
post(this);
} else {
endFling();
if (PROFILE_FLINGING) {
if (mFlingProfilingStarted) {
Debug.stopMethodTracing();
mFlingProfilingStarted = false;
}
}
}
}
}
private void createScrollingCache() {
if (mScrollingCacheEnabled && !mCachingStarted) {
setChildrenDrawnWithCacheEnabled(true);
setChildrenDrawingCacheEnabled(true);
mCachingStarted = true;
}
}
private void clearScrollingCache() {
if (mClearScrollingCache == null) {
mClearScrollingCache = new Runnable() {
public void run() {
if (mCachingStarted) {
mCachingStarted = false;
setChildrenDrawnWithCacheEnabled(false);
if ((mPersistentDrawingCache & PERSISTENT_SCROLLING_CACHE) == 0) {
setChildrenDrawingCacheEnabled(false);
}
if (!isAlwaysDrawnWithCacheEnabled()) {
invalidate();
}
}
}
};
}
post(mClearScrollingCache);
}
/**
* Track a motion scroll
*
* @param deltaY Amount to offset mMotionView. This is the accumulated delta since the motion
* began. Positive numbers mean the user's finger is moving down the screen.
* @param incrementalDeltaY Change in deltaY from the previous event.
*/
void trackMotionScroll(int deltaY, int incrementalDeltaY) {
final int childCount = getChildCount();
if (childCount == 0) {
return;
}
final int firstTop = getChildAt(0).getTop();
final int lastBottom = getChildAt(childCount - 1).getBottom();
final Rect listPadding = mListPadding;
// FIXME account for grid vertical spacing too?
final int spaceAbove = listPadding.top - firstTop;
final int end = getHeight() - listPadding.bottom;
final int spaceBelow = lastBottom - end;
final int height = getHeight() - mPaddingBottom - mPaddingTop;
if (deltaY < 0) {
deltaY = Math.max(-(height - 1), deltaY);
} else {
deltaY = Math.min(height - 1, deltaY);
}
if (incrementalDeltaY < 0) {
incrementalDeltaY = Math.max(-(height - 1), incrementalDeltaY);
} else {
incrementalDeltaY = Math.min(height - 1, incrementalDeltaY);
}
final int absIncrementalDeltaY = Math.abs(incrementalDeltaY);
if (spaceAbove >= absIncrementalDeltaY && spaceBelow >= absIncrementalDeltaY) {
hideSelector();
offsetChildrenTopAndBottom(incrementalDeltaY);
invalidate();
mMotionViewNewTop = mMotionViewOriginalTop + deltaY;
} else {
final int firstPosition = mFirstPosition;
if (firstPosition == 0 && firstTop >= listPadding.top && deltaY > 0) {
// Don't need to move views down if the top of the first position is already visible
return;
}
if (firstPosition + childCount == mItemCount && lastBottom <= end && deltaY < 0) {
// Don't need to move views up if the bottom of the last position is already visible
return;
}
final boolean down = incrementalDeltaY < 0;
hideSelector();
final int headerViewsCount = getHeaderViewsCount();
final int footerViewsStart = mItemCount - getFooterViewsCount();
int start = 0;
int count = 0;
if (down) {
final int top = listPadding.top - incrementalDeltaY;
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getBottom() >= top) {
break;
} else {
count++;
int position = firstPosition + i;
if (position >= headerViewsCount && position < footerViewsStart) {
mRecycler.addScrapView(child);
if (ViewDebug.TRACE_RECYCLER) {
ViewDebug.trace(child,
ViewDebug.RecyclerTraceType.MOVE_TO_SCRAP_HEAP,
firstPosition + i, -1);
}
}
}
}
} else {
final int bottom = getHeight() - listPadding.bottom - incrementalDeltaY;
for (int i = childCount - 1; i >= 0; i--) {
final View child = getChildAt(i);
if (child.getTop() <= bottom) {
break;
} else {
start = i;
count++;
int position = firstPosition + i;
if (position >= headerViewsCount && position < footerViewsStart) {
mRecycler.addScrapView(child);
if (ViewDebug.TRACE_RECYCLER) {
ViewDebug.trace(child,
ViewDebug.RecyclerTraceType.MOVE_TO_SCRAP_HEAP,
firstPosition + i, -1);
}
}
}
}
}
mMotionViewNewTop = mMotionViewOriginalTop + deltaY;
mBlockLayoutRequests = true;
detachViewsFromParent(start, count);
offsetChildrenTopAndBottom(incrementalDeltaY);
if (down) {
mFirstPosition += count;
}
invalidate();
fillGap(down);
mBlockLayoutRequests = false;
invokeOnItemScrollListener();
}
}
/**
* Returns the number of header views in the list. Header views are special views
* at the top of the list that should not be recycled during a layout.
*
* @return The number of header views, 0 in the default implementation.
*/
int getHeaderViewsCount() {
return 0;
}
/**
* Returns the number of footer views in the list. Footer views are special views
* at the bottom of the list that should not be recycled during a layout.
*
* @return The number of footer views, 0 in the default implementation.
*/
int getFooterViewsCount() {
return 0;
}
/**
* Fills the gap left open by a touch-scroll. During a touch scroll, children that
* remain on screen are shifted and the other ones are discarded. The role of this
* method is to fill the gap thus created by performing a partial layout in the
* empty space.
*
* @param down true if the scroll is going down, false if it is going up
*/
abstract void fillGap(boolean down);
void hideSelector() {
if (mSelectedPosition != INVALID_POSITION) {
mResurrectToPosition = mSelectedPosition;
if (mNextSelectedPosition >= 0 && mNextSelectedPosition != mSelectedPosition) {
mResurrectToPosition = mNextSelectedPosition;
}
setSelectedPositionInt(INVALID_POSITION);
setNextSelectedPositionInt(INVALID_POSITION);
mSelectedTop = 0;
mSelectorRect.setEmpty();
}
}
/**
* @return A position to select. First we try mSelectedPosition. If that has been clobbered by
* entering touch mode, we then try mResurrectToPosition. Values are pinned to the range
* of items available in the adapter
*/
int reconcileSelectedPosition() {
int position = mSelectedPosition;
if (position < 0) {
position = mResurrectToPosition;
}
position = Math.max(0, position);
position = Math.min(position, mItemCount - 1);
return position;
}
/**
* Find the row closest to y. This row will be used as the motion row when scrolling
*
* @param y Where the user touched
* @return The position of the first (or only) item in the row closest to y
*/
abstract int findMotionRow(int y);
/**
* Causes all the views to be rebuilt and redrawn.
*/
public void invalidateViews() {
mDataChanged = true;
rememberSyncState();
requestLayout();
invalidate();
}
/**
* Makes the item at the supplied position selected.
*
* @param position the position of the new selection
*/
abstract void setSelectionInt(int position);
/**
* Attempt to bring the selection back if the user is switching from touch
* to trackball mode
* @return Whether selection was set to something.
*/
boolean resurrectSelection() {
final int childCount = getChildCount();
if (childCount <= 0) {
return false;
}
int selectedTop = 0;
int selectedPos;
int childrenTop = mListPadding.top;
int childrenBottom = mBottom - mTop - mListPadding.bottom;
final int firstPosition = mFirstPosition;
final int toPosition = mResurrectToPosition;
boolean down = true;
if (toPosition >= firstPosition && toPosition < firstPosition + childCount) {
selectedPos = toPosition;
final View selected = getChildAt(selectedPos - mFirstPosition);
selectedTop = selected.getTop();
int selectedBottom = selected.getBottom();
// We are scrolled, don't get in the fade
if (selectedTop < childrenTop) {
selectedTop = childrenTop + getVerticalFadingEdgeLength();
} else if (selectedBottom > childrenBottom) {
selectedTop = childrenBottom - selected.getMeasuredHeight()
- getVerticalFadingEdgeLength();
}
} else {
if (toPosition < firstPosition) {
// Default to selecting whatever is first
selectedPos = firstPosition;
for (int i = 0; i < childCount; i++) {
final View v = getChildAt(i);
final int top = v.getTop();
if (i == 0) {
// Remember the position of the first item
selectedTop = top;
// See if we are scrolled at all
if (firstPosition > 0 || top < childrenTop) {
// If we are scrolled, don't select anything that is
// in the fade region
childrenTop += getVerticalFadingEdgeLength();
}
}
if (top >= childrenTop) {
// Found a view whose top is fully visisble
selectedPos = firstPosition + i;
selectedTop = top;
break;
}
}
} else {
final int itemCount = mItemCount;
down = false;
selectedPos = firstPosition + childCount - 1;
for (int i = childCount - 1; i >= 0; i--) {
final View v = getChildAt(i);
final int top = v.getTop();
final int bottom = v.getBottom();
if (i == childCount - 1) {
selectedTop = top;
if (firstPosition + childCount < itemCount || bottom > childrenBottom) {
childrenBottom -= getVerticalFadingEdgeLength();
}
}
if (bottom <= childrenBottom) {
selectedPos = firstPosition + i;
selectedTop = top;
break;
}
}
}
}
mResurrectToPosition = INVALID_POSITION;
removeCallbacks(mFlingRunnable);
mTouchMode = TOUCH_MODE_REST;
clearScrollingCache();
mSpecificTop = selectedTop;
selectedPos = lookForSelectablePosition(selectedPos, down);
if (selectedPos >= firstPosition && selectedPos <= getLastVisiblePosition()) {
mLayoutMode = LAYOUT_SPECIFIC;
setSelectionInt(selectedPos);
invokeOnItemScrollListener();
} else {
selectedPos = INVALID_POSITION;
}
reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
return selectedPos >= 0;
}
@Override
protected void handleDataChanged() {
int count = mItemCount;
if (count > 0) {
int newPos;
int selectablePos;
// Find the row we are supposed to sync to
if (mNeedSync) {
// Update this first, since setNextSelectedPositionInt inspects it
mNeedSync = false;
if (mTranscriptMode == TRANSCRIPT_MODE_ALWAYS_SCROLL ||
(mTranscriptMode == TRANSCRIPT_MODE_NORMAL &&
mFirstPosition + getChildCount() >= mOldItemCount)) {
mLayoutMode = LAYOUT_FORCE_BOTTOM;
return;
}
switch (mSyncMode) {
case SYNC_SELECTED_POSITION:
if (isInTouchMode()) {
// We saved our state when not in touch mode. (We know this because
// mSyncMode is SYNC_SELECTED_POSITION.) Now we are trying to
// restore in touch mode. Just leave mSyncPosition as it is (possibly
// adjusting if the available range changed) and return.
mLayoutMode = LAYOUT_SYNC;
mSyncPosition = Math.min(Math.max(0, mSyncPosition), count - 1);
return;
} else {
// See if we can find a position in the new data with the same
// id as the old selection. This will change mSyncPosition.
newPos = findSyncPosition();
if (newPos >= 0) {
// Found it. Now verify that new selection is still selectable
selectablePos = lookForSelectablePosition(newPos, true);
if (selectablePos == newPos) {
// Same row id is selected
mSyncPosition = newPos;
if (mSyncHeight == getHeight()) {
// If we are at the same height as when we saved state, try
// to restore the scroll position too.
mLayoutMode = LAYOUT_SYNC;
} else {
// We are not the same height as when the selection was saved, so
// don't try to restore the exact position
mLayoutMode = LAYOUT_SET_SELECTION;
}
// Restore selection
setNextSelectedPositionInt(newPos);
return;
}
}
}
break;
case SYNC_FIRST_POSITION:
// Leave mSyncPosition as it is -- just pin to available range
mLayoutMode = LAYOUT_SYNC;
mSyncPosition = Math.min(Math.max(0, mSyncPosition), count - 1);
return;
}
}
if (!isInTouchMode()) {
// We couldn't find matching data -- try to use the same position
newPos = getSelectedItemPosition();
// Pin position to the available range
if (newPos >= count) {
newPos = count - 1;
}
if (newPos < 0) {
newPos = 0;
}
// Make sure we select something selectable -- first look down
selectablePos = lookForSelectablePosition(newPos, true);
if (selectablePos >= 0) {
setNextSelectedPositionInt(selectablePos);
return;
} else {
// Looking down didn't work -- try looking up
selectablePos = lookForSelectablePosition(newPos, false);
if (selectablePos >= 0) {
setNextSelectedPositionInt(selectablePos);
return;
}
}
} else {
// We already know where we want to resurrect the selection
if (mResurrectToPosition >= 0) {
return;
}
}
}
// Nothing is selected. Give up and reset everything.
mLayoutMode = mStackFromBottom ? LAYOUT_FORCE_BOTTOM : LAYOUT_FORCE_TOP;
mSelectedPosition = INVALID_POSITION;
mSelectedRowId = INVALID_ROW_ID;
mNextSelectedPosition = INVALID_POSITION;
mNextSelectedRowId = INVALID_ROW_ID;
mNeedSync = false;
checkSelectionChanged();
}
/**
* Removes the filter window
*/
private void dismissPopup() {
if (mPopup != null) {
mPopup.dismiss();
}
}
/**
* Shows the filter window
*/
private void showPopup() {
// Make sure we have a window before showing the popup
if (getWindowVisibility() == View.VISIBLE) {
createTextFilter(true);
positionPopup();
// Make sure we get focus if we are showing the popup
checkFocus();
}
}
private void positionPopup() {
int screenHeight = getResources().getDisplayMetrics().heightPixels;
final int[] xy = new int[2];
getLocationOnScreen(xy);
// TODO: The 20 below should come from the theme
// TODO: And the gravity should be defined in the theme as well
final int bottomGap = screenHeight - xy[1] - getHeight() + (int) (mDensityScale * 20);
if (!mPopup.isShowing()) {
mPopup.showAtLocation(this, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL,
xy[0], bottomGap);
} else {
mPopup.update(xy[0], bottomGap, -1, -1);
}
}
/**
* What is the distance between the source and destination rectangles given the direction of
* focus navigation between them? The direction basically helps figure out more quickly what is
* self evident by the relationship between the rects...
*
* @param source the source rectangle
* @param dest the destination rectangle
* @param direction the direction
* @return the distance between the rectangles
*/
static int getDistance(Rect source, Rect dest, int direction) {
int sX, sY; // source x, y
int dX, dY; // dest x, y
switch (direction) {
case View.FOCUS_RIGHT:
sX = source.right;
sY = source.top + source.height() / 2;
dX = dest.left;
dY = dest.top + dest.height() / 2;
break;
case View.FOCUS_DOWN:
sX = source.left + source.width() / 2;
sY = source.bottom;
dX = dest.left + dest.width() / 2;
dY = dest.top;
break;
case View.FOCUS_LEFT:
sX = source.left;
sY = source.top + source.height() / 2;
dX = dest.right;
dY = dest.top + dest.height() / 2;
break;
case View.FOCUS_UP:
sX = source.left + source.width() / 2;
sY = source.top;
dX = dest.left + dest.width() / 2;
dY = dest.bottom;
break;
default:
throw new IllegalArgumentException("direction must be one of "
+ "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT}.");
}
int deltaX = dX - sX;
int deltaY = dY - sY;
return deltaY * deltaY + deltaX * deltaX;
}
@Override
protected boolean isInFilterMode() {
return mFiltered;
}
/**
* Sends a key to the text filter window
*
* @param keyCode The keycode for the event
* @param event The actual key event
*
* @return True if the text filter handled the event, false otherwise.
*/
boolean sendToTextFilter(int keyCode, int count, KeyEvent event) {
if (!acceptFilter()) {
return false;
}
boolean handled = false;
boolean okToSend = true;
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
okToSend = false;
break;
case KeyEvent.KEYCODE_BACK:
if (mFiltered && mPopup != null && mPopup.isShowing() &&
event.getAction() == KeyEvent.ACTION_DOWN) {
handled = true;
mTextFilter.setText("");
}
okToSend = false;
break;
case KeyEvent.KEYCODE_SPACE:
// Only send spaces once we are filtered
okToSend = mFiltered = true;
break;
}
if (okToSend) {
createTextFilter(true);
KeyEvent forwardEvent = event;
if (forwardEvent.getRepeatCount() > 0) {
forwardEvent = KeyEvent.changeTimeRepeat(event, event.getEventTime(), 0);
}
int action = event.getAction();
switch (action) {
case KeyEvent.ACTION_DOWN:
handled = mTextFilter.onKeyDown(keyCode, forwardEvent);
break;
case KeyEvent.ACTION_UP:
handled = mTextFilter.onKeyUp(keyCode, forwardEvent);
break;
case KeyEvent.ACTION_MULTIPLE:
handled = mTextFilter.onKeyMultiple(keyCode, count, event);
break;
}
}
return handled;
}
/**
* Return an InputConnection for editing of the filter text.
*/
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
if (isTextFilterEnabled()) {
// XXX we need to have the text filter created, so we can get an
// InputConnection to proxy to. Unfortunately this means we pretty
// much need to make it as soon as a list view gets focus.
createTextFilter(false);
if (mPublicInputConnection == null) {
mDefInputConnection = new BaseInputConnection(this, false);
mPublicInputConnection = new InputConnectionWrapper(
mTextFilter.onCreateInputConnection(outAttrs), true) {
@Override
public boolean reportFullscreenMode(boolean enabled) {
// Use our own input connection, since it is
// the "real" one the IME is talking with.
return mDefInputConnection.reportFullscreenMode(enabled);
}
@Override
public boolean performEditorAction(int editorAction) {
// The editor is off in its own window; we need to be
// the one that does this.
if (editorAction == EditorInfo.IME_ACTION_DONE) {
InputMethodManager imm = (InputMethodManager)
getContext().getSystemService(
Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(getWindowToken(), 0);
}
return true;
}
return false;
}
@Override
public boolean sendKeyEvent(KeyEvent event) {
// Use our own input connection, since the filter
// text view may not be shown in a window so has
// no ViewRoot to dispatch events with.
return mDefInputConnection.sendKeyEvent(event);
}
};
}
outAttrs.inputType = EditorInfo.TYPE_CLASS_TEXT
| EditorInfo.TYPE_TEXT_VARIATION_FILTER;
outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE;
return mPublicInputConnection;
}
return null;
}
/**
* For filtering we proxy an input connection to an internal text editor,
* and this allows the proxying to happen.
*/
@Override
public boolean checkInputConnectionProxy(View view) {
return view == mTextFilter;
}
/**
* Creates the window for the text filter and populates it with an EditText field;
*
* @param animateEntrance true if the window should appear with an animation
*/
private void createTextFilter(boolean animateEntrance) {
if (mPopup == null) {
Context c = getContext();
PopupWindow p = new PopupWindow(c);
LayoutInflater layoutInflater = (LayoutInflater)
c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mTextFilter = (EditText) layoutInflater.inflate(
com.android.internal.R.layout.typing_filter, null);
// For some reason setting this as the "real" input type changes
// the text view in some way that it doesn't work, and I don't
// want to figure out why this is.
mTextFilter.setRawInputType(EditorInfo.TYPE_CLASS_TEXT
| EditorInfo.TYPE_TEXT_VARIATION_FILTER);
mTextFilter.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
mTextFilter.addTextChangedListener(this);
p.setFocusable(false);
p.setTouchable(false);
p.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
p.setContentView(mTextFilter);
p.setWidth(LayoutParams.WRAP_CONTENT);
p.setHeight(LayoutParams.WRAP_CONTENT);
p.setBackgroundDrawable(null);
mPopup = p;
getViewTreeObserver().addOnGlobalLayoutListener(this);
mGlobalLayoutListenerAddedFilter = true;
}
if (animateEntrance) {
mPopup.setAnimationStyle(com.android.internal.R.style.Animation_TypingFilter);
} else {
mPopup.setAnimationStyle(com.android.internal.R.style.Animation_TypingFilterRestore);
}
}
/**
* Clear the text filter.
*/
public void clearTextFilter() {
if (mFiltered) {
mTextFilter.setText("");
mFiltered = false;
if (mPopup != null && mPopup.isShowing()) {
dismissPopup();
}
}
}
/**
* Returns if the ListView currently has a text filter.
*/
public boolean hasTextFilter() {
return mFiltered;
}
public void onGlobalLayout() {
if (isShown()) {
// Show the popup if we are filtered
if (mFiltered && mPopup != null && !mPopup.isShowing()) {
showPopup();
}
} else {
// Hide the popup when we are no longer visible
if (mPopup.isShowing()) {
dismissPopup();
}
}
}
/**
* For our text watcher that is associated with the text filter. Does
* nothing.
*/
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
/**
* For our text watcher that is associated with the text filter. Performs
* the actual filtering as the text changes, and takes care of hiding and
* showing the popup displaying the currently entered filter text.
*/
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (mPopup != null && isTextFilterEnabled()) {
int length = s.length();
boolean showing = mPopup.isShowing();
if (!showing && length > 0) {
// Show the filter popup if necessary
showPopup();
mFiltered = true;
} else if (showing && length == 0) {
// Remove the filter popup if the user has cleared all text
dismissPopup();
mFiltered = false;
}
if (mAdapter instanceof Filterable) {
Filter f = ((Filterable) mAdapter).getFilter();
// Filter should not be null when we reach this part
if (f != null) {
f.filter(s, this);
} else {
throw new IllegalStateException("You cannot call onTextChanged with a non "
+ "filterable adapter");
}
}
}
}
/**
* For our text watcher that is associated with the text filter. Does
* nothing.
*/
public void afterTextChanged(Editable s) {
}
public void onFilterComplete(int count) {
if (mSelectedPosition < 0 && count > 0) {
mResurrectToPosition = INVALID_POSITION;
resurrectSelection();
}
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return new LayoutParams(p);
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new AbsListView.LayoutParams(getContext(), attrs);
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof AbsListView.LayoutParams;
}
/**
* Puts the list or grid into transcript mode. In this mode the list or grid will always scroll
* to the bottom to show new items.
*
* @param mode the transcript mode to set
*
* @see #TRANSCRIPT_MODE_DISABLED
* @see #TRANSCRIPT_MODE_NORMAL
* @see #TRANSCRIPT_MODE_ALWAYS_SCROLL
*/
public void setTranscriptMode(int mode) {
mTranscriptMode = mode;
}
/**
* Returns the current transcript mode.
*
* @return {@link #TRANSCRIPT_MODE_DISABLED}, {@link #TRANSCRIPT_MODE_NORMAL} or
* {@link #TRANSCRIPT_MODE_ALWAYS_SCROLL}
*/
public int getTranscriptMode() {
return mTranscriptMode;
}
@Override
public int getSolidColor() {
return mCacheColorHint;
}
/**
* When set to a non-zero value, the cache color hint indicates that this list is always drawn
* on top of a solid, single-color, opaque background
*
* @param color The background color
*/
public void setCacheColorHint(int color) {
mCacheColorHint = color;
}
/**
* When set to a non-zero value, the cache color hint indicates that this list is always drawn
* on top of a solid, single-color, opaque background
*
* @return The cache color hint
*/
public int getCacheColorHint() {
return mCacheColorHint;
}
/**
* Move all views (excluding headers and footers) held by this AbsListView into the supplied
* List. This includes views displayed on the screen as well as views stored in AbsListView's
* internal view recycler.
*
* @param views A list into which to put the reclaimed views
*/
public void reclaimViews(List<View> views) {
int childCount = getChildCount();
RecyclerListener listener = mRecycler.mRecyclerListener;
// Reclaim views on screen
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
AbsListView.LayoutParams lp = (AbsListView.LayoutParams) child.getLayoutParams();
// Don't reclaim header or footer views, or views that should be ignored
if (lp != null && mRecycler.shouldRecycleViewType(lp.viewType)) {
views.add(child);
if (listener != null) {
// Pretend they went through the scrap heap
listener.onMovedToScrapHeap(child);
}
}
}
mRecycler.reclaimScrapViews(views);
removeAllViewsInLayout();
}
/**
* @hide
*/
@Override
protected boolean onConsistencyCheck(int consistency) {
boolean result = super.onConsistencyCheck(consistency);
final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
if (checkLayout) {
// The active recycler must be empty
final View[] activeViews = mRecycler.mActiveViews;
int count = activeViews.length;
for (int i = 0; i < count; i++) {
if (activeViews[i] != null) {
result = false;
android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
"AbsListView " + this + " has a view in its active recycler: " +
activeViews[i]);
}
}
// All views in the recycler must NOT be on screen and must NOT have a parent
final ArrayList<View> scrap = mRecycler.mCurrentScrap;
if (!checkScrap(scrap)) result = false;
final ArrayList<View>[] scraps = mRecycler.mScrapViews;
count = scraps.length;
for (int i = 0; i < count; i++) {
if (!checkScrap(scraps[i])) result = false;
}
}
return result;
}
private boolean checkScrap(ArrayList<View> scrap) {
if (scrap == null) return true;
boolean result = true;
final int count = scrap.size();
for (int i = 0; i < count; i++) {
final View view = scrap.get(i);
if (view.getParent() != null) {
result = false;
android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, "AbsListView " + this +
" has a view in its scrap heap still attached to a parent: " + view);
}
if (indexOfChild(view) >= 0) {
result = false;
android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, "AbsListView " + this +
" has a view in its scrap heap that is also a direct child: " + view);
}
}
return result;
}
/**
* Sets the recycler listener to be notified whenever a View is set aside in
* the recycler for later reuse. This listener can be used to free resources
* associated to the View.
*
* @param listener The recycler listener to be notified of views set aside
* in the recycler.
*
* @see android.widget.AbsListView.RecycleBin
* @see android.widget.AbsListView.RecyclerListener
*/
public void setRecyclerListener(RecyclerListener listener) {
mRecycler.mRecyclerListener = listener;
}
/**
* AbsListView extends LayoutParams to provide a place to hold the view type.
*/
public static class LayoutParams extends ViewGroup.LayoutParams {
/**
* View type for this view, as returned by
* {@link android.widget.Adapter#getItemViewType(int) }
*/
int viewType;
/**
* When this boolean is set, the view has been added to the AbsListView
* at least once. It is used to know whether headers/footers have already
* been added to the list view and whether they should be treated as
* recycled views or not.
*/
boolean recycledHeaderFooter;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(int w, int h) {
super(w, h);
}
public LayoutParams(int w, int h, int viewType) {
super(w, h);
this.viewType = viewType;
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
}
/**
* A RecyclerListener is used to receive a notification whenever a View is placed
* inside the RecycleBin's scrap heap. This listener is used to free resources
* associated to Views placed in the RecycleBin.
*
* @see android.widget.AbsListView.RecycleBin
* @see android.widget.AbsListView#setRecyclerListener(android.widget.AbsListView.RecyclerListener)
*/
public static interface RecyclerListener {
/**
* Indicates that the specified View was moved into the recycler's scrap heap.
* The view is not displayed on screen any more and any expensive resource
* associated with the view should be discarded.
*
* @param view
*/
void onMovedToScrapHeap(View view);
}
/**
* The RecycleBin facilitates reuse of views across layouts. The RecycleBin has two levels of
* storage: ActiveViews and ScrapViews. ActiveViews are those views which were onscreen at the
* start of a layout. By construction, they are displaying current information. At the end of
* layout, all views in ActiveViews are demoted to ScrapViews. ScrapViews are old views that
* could potentially be used by the adapter to avoid allocating views unnecessarily.
*
* @see android.widget.AbsListView#setRecyclerListener(android.widget.AbsListView.RecyclerListener)
* @see android.widget.AbsListView.RecyclerListener
*/
class RecycleBin {
private RecyclerListener mRecyclerListener;
/**
* The position of the first view stored in mActiveViews.
*/
private int mFirstActivePosition;
/**
* Views that were on screen at the start of layout. This array is populated at the start of
* layout, and at the end of layout all view in mActiveViews are moved to mScrapViews.
* Views in mActiveViews represent a contiguous range of Views, with position of the first
* view store in mFirstActivePosition.
*/
private View[] mActiveViews = new View[0];
/**
* Unsorted views that can be used by the adapter as a convert view.
*/
private ArrayList<View>[] mScrapViews;
private int mViewTypeCount;
private ArrayList<View> mCurrentScrap;
public void setViewTypeCount(int viewTypeCount) {
if (viewTypeCount < 1) {
throw new IllegalArgumentException("Can't have a viewTypeCount < 1");
}
//noinspection unchecked
ArrayList<View>[] scrapViews = new ArrayList[viewTypeCount];
for (int i = 0; i < viewTypeCount; i++) {
scrapViews[i] = new ArrayList<View>();
}
mViewTypeCount = viewTypeCount;
mCurrentScrap = scrapViews[0];
mScrapViews = scrapViews;
}
public boolean shouldRecycleViewType(int viewType) {
return viewType >= 0;
}
/**
* Clears the scrap heap.
*/
void clear() {
if (mViewTypeCount == 1) {
final ArrayList<View> scrap = mCurrentScrap;
final int scrapCount = scrap.size();
for (int i = 0; i < scrapCount; i++) {
removeDetachedView(scrap.remove(scrapCount - 1 - i), false);
}
} else {
final int typeCount = mViewTypeCount;
for (int i = 0; i < typeCount; i++) {
final ArrayList<View> scrap = mScrapViews[i];
final int scrapCount = scrap.size();
for (int j = 0; j < scrapCount; j++) {
removeDetachedView(scrap.remove(scrapCount - 1 - j), false);
}
}
}
}
/**
* Fill ActiveViews with all of the children of the AbsListView.
*
* @param childCount The minimum number of views mActiveViews should hold
* @param firstActivePosition The position of the first view that will be stored in
* mActiveViews
*/
void fillActiveViews(int childCount, int firstActivePosition) {
if (mActiveViews.length < childCount) {
mActiveViews = new View[childCount];
}
mFirstActivePosition = firstActivePosition;
final View[] activeViews = mActiveViews;
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
AbsListView.LayoutParams lp = (AbsListView.LayoutParams)child.getLayoutParams();
// Don't put header or footer views into the scrap heap
if (lp != null && lp.viewType != AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER) {
// Note: We do place AdapterView.ITEM_VIEW_TYPE_IGNORE in active views.
// However, we will NOT place them into scrap views.
activeViews[i] = child;
}
}
}
/**
* Get the view corresponding to the specified position. The view will be removed from
* mActiveViews if it is found.
*
* @param position The position to look up in mActiveViews
* @return The view if it is found, null otherwise
*/
View getActiveView(int position) {
int index = position - mFirstActivePosition;
final View[] activeViews = mActiveViews;
if (index >=0 && index < activeViews.length) {
final View match = activeViews[index];
activeViews[index] = null;
return match;
}
return null;
}
/**
* @return A view from the ScrapViews collection. These are unordered.
*/
View getScrapView(int position) {
ArrayList<View> scrapViews;
if (mViewTypeCount == 1) {
scrapViews = mCurrentScrap;
int size = scrapViews.size();
if (size > 0) {
return scrapViews.remove(size - 1);
} else {
return null;
}
} else {
int whichScrap = mAdapter.getItemViewType(position);
if (whichScrap >= 0 && whichScrap < mScrapViews.length) {
scrapViews = mScrapViews[whichScrap];
int size = scrapViews.size();
if (size > 0) {
return scrapViews.remove(size - 1);
}
}
}
return null;
}
/**
* Put a view into the ScapViews list. These views are unordered.
*
* @param scrap The view to add
*/
void addScrapView(View scrap) {
AbsListView.LayoutParams lp = (AbsListView.LayoutParams) scrap.getLayoutParams();
if (lp == null) {
return;
}
// Don't put header or footer views or views that should be ignored
// into the scrap heap
int viewType = lp.viewType;
if (!shouldRecycleViewType(viewType)) {
return;
}
if (mViewTypeCount == 1) {
mCurrentScrap.add(scrap);
} else {
mScrapViews[viewType].add(scrap);
}
if (mRecyclerListener != null) {
mRecyclerListener.onMovedToScrapHeap(scrap);
}
}
/**
* Move all views remaining in mActiveViews to mScrapViews.
*/
void scrapActiveViews() {
final View[] activeViews = mActiveViews;
final boolean hasListener = mRecyclerListener != null;
final boolean multipleScraps = mViewTypeCount > 1;
ArrayList<View> scrapViews = mCurrentScrap;
final int count = activeViews.length;
for (int i = 0; i < count; ++i) {
final View victim = activeViews[i];
if (victim != null) {
int whichScrap = ((AbsListView.LayoutParams)
victim.getLayoutParams()).viewType;
activeViews[i] = null;
if (whichScrap == AdapterView.ITEM_VIEW_TYPE_IGNORE) {
// Do not move views that should be ignored
continue;
}
if (multipleScraps) {
scrapViews = mScrapViews[whichScrap];
}
scrapViews.add(victim);
if (hasListener) {
mRecyclerListener.onMovedToScrapHeap(victim);
}
if (ViewDebug.TRACE_RECYCLER) {
ViewDebug.trace(victim,
ViewDebug.RecyclerTraceType.MOVE_FROM_ACTIVE_TO_SCRAP_HEAP,
mFirstActivePosition + i, -1);
}
}
}
pruneScrapViews();
}
/**
* Makes sure that the size of mScrapViews does not exceed the size of mActiveViews.
* (This can happen if an adapter does not recycle its views).
*/
private void pruneScrapViews() {
final int maxViews = mActiveViews.length;
final int viewTypeCount = mViewTypeCount;
final ArrayList<View>[] scrapViews = mScrapViews;
for (int i = 0; i < viewTypeCount; ++i) {
final ArrayList<View> scrapPile = scrapViews[i];
int size = scrapPile.size();
final int extras = size - maxViews;
size--;
for (int j = 0; j < extras; j++) {
removeDetachedView(scrapPile.remove(size--), false);
}
}
}
/**
* Puts all views in the scrap heap into the supplied list.
*/
void reclaimScrapViews(List<View> views) {
if (mViewTypeCount == 1) {
views.addAll(mCurrentScrap);
} else {
final int viewTypeCount = mViewTypeCount;
final ArrayList<View>[] scrapViews = mScrapViews;
for (int i = 0; i < viewTypeCount; ++i) {
final ArrayList<View> scrapPile = scrapViews[i];
views.addAll(scrapPile);
}
}
}
}
private class GesturesProcessor implements
TouchThroughGestureListener.OnGesturePerformedListener {
private static final double SCORE_THRESHOLD = 0.1;
private LetterRecognizer mRecognizer;
private ArrayList<Prediction> mPredictions;
private final KeyCharacterMap mKeyMap;
private final char[] mHolder;
GesturesProcessor() {
mRecognizer = LetterRecognizer.getLetterRecognizer(getContext(),
LetterRecognizer.RECOGNIZER_LATIN_LOWERCASE);
if (mGestures == GESTURES_FILTER) {
mKeyMap = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
mHolder = new char[1];
} else {
mKeyMap = null;
mHolder = null;
}
}
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
mPredictions = mRecognizer.recognize(gesture, mPredictions);
if (!mPredictions.isEmpty()) {
final Prediction prediction = mPredictions.get(0);
if (prediction.score > SCORE_THRESHOLD) {
switch (mGestures) {
case GESTURES_JUMP:
processJump(prediction);
break;
case GESTURES_FILTER:
processFilter(prediction);
break;
}
}
}
}
private void processJump(Prediction prediction) {
final Object[] sections = mFastScroller.getSections();
if (sections != null) {
final String name = prediction.name;
final int count = sections.length;
int index = -1;
for (int i = 0; i < count; i++) {
if (name.equalsIgnoreCase((String) sections[i])) {
index = i;
break;
}
}
if (index != -1) {
final SectionIndexer indexer = mFastScroller.getSectionIndexer();
final int position = indexer.getPositionForSection(index);
setSelection(position);
}
}
}
private void processFilter(Prediction prediction) {
mHolder[0] = prediction.name.charAt(0);
final KeyEvent[] events = mKeyMap.getEvents(mHolder);
if (events != null) {
for (KeyEvent event : events) {
sendToTextFilter(event.getKeyCode(), event.getRepeatCount(),
event);
}
}
}
}
}
|