forked from soarcn/BottomSheet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBottomSheet.java
More file actions
618 lines (540 loc) · 20.5 KB
/
BottomSheet.java
File metadata and controls
618 lines (540 loc) · 20.5 KB
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
package com.cocosw.bottomsheet;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.DrawableRes;
import android.support.annotation.MenuRes;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.annotation.StyleRes;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ItemAnimator.ItemAnimatorFinishedListener;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import com.cocosw.bottomsheet.utils.BuildHelper;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* One way to present a set of actions to a user is with bottom sheets, a sheet of paper that slides up from the bottom edge of the screen. Bottom sheets offer flexibility in the display of clear and simple actions that do not need explanation.
*
* https://www.google.com/design/spec/components/bottom-sheets.html
*
* Project: BottomSheet
* Created by LiaoKai(soarcn) on 2014/9/21.
*/
public class BottomSheet extends Dialog implements DialogInterface, View.OnClickListener {
private static final long RIPPLE_ANIM_LENGTH = 350;
private RecyclerView list;
private BottomSheetAdapter adapter;
// Builder Props
private List<BSItem> bsItems;
private Dialog.OnClickListener dialogListener;
private CharSequence text;
private boolean isGrid;
// translucent support
private static final String NAV_BAR_HEIGHT_RES_NAME = "navigation_bar_height";
private static final String NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME = "navigation_bar_height_landscape";
private static final String SHOW_NAV_BAR_RES_NAME = "config_showNavigationBar";
private boolean mInPortrait;
private String sNavBarOverride;
private boolean mNavBarAvailable;
private float mSmallestWidthDp;
private int itemHeight;
private BottomSheet(Builder builder) {
super(builder.activity, builder.theme);
// https://github.com/jgilfelt/SystemBarTint/blob/master/library/src/com/readystatesoftware/systembartint/SystemBarTintManager.java
if (BuildHelper.HAS_KITKAT) {
reflectOnNavBar();
mInPortrait = (getContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
setupTheme();
setupWindow(builder);
}
setCanceledOnTouchOutside(true);
setPropertiesFromBuilder(builder);
}
@TargetApi(19)
private void setupWindow(Builder builder) {
WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams winParams = (builder.activity).getWindow().getAttributes();
int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
if ((winParams.flags & bits) != 0) {
mNavBarAvailable = true;
}
mSmallestWidthDp = getSmallestWidthDp(wm);
if (mNavBarAvailable)
setTranslucentStatus(true);
}
@TargetApi(19)
private void setTranslucentStatus(boolean on) {
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
// instance
win.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
@TargetApi(19)
/** Let's be honest, reflecting on the system is bad. */
private void reflectOnNavBar() {
try {
Class c = Class.forName("android.os.SystemProperties");
Method m = c.getDeclaredMethod("get", String.class);
m.setAccessible(true);
sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
} catch (Throwable e) {
sNavBarOverride = null;
}
}
@TargetApi(19)
private void setupTheme() {
int[] as = {android.R.attr.windowTranslucentStatus,
android.R.attr.windowTranslucentNavigation};
TypedArray a = getContext().obtainStyledAttributes(as);
try {
mNavBarAvailable = a.getBoolean(1, false);
} finally {
a.recycle();
}
}
private void setPropertiesFromBuilder(Builder builder) {
dialogListener = builder.listener;
text = builder.title;
isGrid = builder.isGrid;
bsItems = builder.bsItems;
// Grid mode does not support divider, we will remove them all here
if (builder.isGrid) {
Iterator<BSItem> i = bsItems.iterator();
while (i.hasNext()) {
BSItem item = i.next();
if (item.isDivider()) {
i.remove();
}
else if (item.getIcon()==null) {
throw new IllegalArgumentException("You should set icon for each items in isGrid style");
}
}
}
}
@SuppressLint("NewApi")
private float getSmallestWidthDp(WindowManager wm) {
DisplayMetrics metrics = new DisplayMetrics();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
wm.getDefaultDisplay().getRealMetrics(metrics);
} else {
//this is not correct, but we don't really care pre-kitkat
wm.getDefaultDisplay().getMetrics(metrics);
}
float widthDp = metrics.widthPixels / metrics.density;
float heightDp = metrics.heightPixels / metrics.density;
return Math.min(widthDp, heightDp);
}
@TargetApi(14)
private int getNavigationBarHeight(Context context) {
Resources res = context.getResources();
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
if (hasNavBar(context)) {
String key;
if (mInPortrait) {
key = NAV_BAR_HEIGHT_RES_NAME;
} else {
if (!isNavigationAtBottom())
return 0;
key = NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME;
}
return getInternalDimensionSize(res, key);
}
}
return result;
}
@TargetApi(14)
private boolean hasNavBar(Context context) {
Resources res = context.getResources();
int resourceId = res.getIdentifier(SHOW_NAV_BAR_RES_NAME, "bool", "android");
if (resourceId != 0) {
boolean hasNav = res.getBoolean(resourceId);
// check override flag (see static block)
if ("1".equals(sNavBarOverride)) {
hasNav = false;
} else if ("0".equals(sNavBarOverride)) {
hasNav = true;
}
return hasNav;
} else { // fallback
return !ViewConfiguration.get(context).hasPermanentMenuKey();
}
}
@Override
public void onClick(View view) {
if (dialogListener != null) {
dialogListener.onClick(BottomSheet.this, (Integer) view.getTag());
}
}
private int getInternalDimensionSize(Resources res, String key) {
int result = 0;
int resourceId = res.getIdentifier(key, "dimen", "android");
if (resourceId > 0) {
result = res.getDimensionPixelSize(resourceId);
}
return result;
}
/**
* Should a navigation bar appear at the bottom of the screen in the current
* device configuration? A navigation bar may appear on the right side of
* the screen in certain configurations.
*
* @return True if navigation should appear at the bottom of the screen, False otherwise.
*/
private boolean isNavigationAtBottom() {
return (mSmallestWidthDp >= 600 || mInPortrait);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
inflateViews(getContext());
setDialogLocation();
}
@Override
protected void onStart() {
super.onStart();
postInvalidateDialogLayout();
}
private void inflateViews(Context context) {
View dialogView = View.inflate(context, R.layout.bs_bottom_sheet_dialog, null);
setContentView(dialogView);
this.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
list.startLayoutAnimation();
}
});
if (BuildHelper.HAS_KITKAT && mNavBarAvailable) {
dialogView.setPadding(0, 0, 0, getNavigationBarHeight(getContext())+dialogView.getPaddingBottom());
}
TextView title = (TextView) dialogView.findViewById(R.id.bottom_sheet_title);
if (text != null) {
title.setVisibility(View.VISIBLE);
title.setText(text);
}
setupListView(dialogView);
}
private void setupListView(View dialogView) {
Context context = getContext();
list = (RecyclerView) dialogView.findViewById(R.id.bottom_sheet_recyclerview);
if (isGrid) {
list.setLayoutManager(new GridLayoutManager(context, context.getResources().getInteger(R.integer.bs_grid_colum)));
} else {
list.setLayoutManager(new LinearLayoutManager(context));
}
list.setAdapter(getAdapter());
list.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < 16) {
//noinspection deprecation
list.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
list.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
View lastChild = list.getChildAt(list.getChildCount() - 1);
if (lastChild != null) {
itemHeight = lastChild.getHeight() + lastChild.getPaddingTop() + lastChild.getPaddingBottom();
}
}
});
}
private void setDialogLocation() {
WindowManager.LayoutParams params = getWindow().getAttributes();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
params.gravity = Gravity.BOTTOM;
getWindow().setAttributes(params);
}
private BottomSheetAdapter getAdapter() {
if (adapter == null) {
adapter = new BottomSheetAdapter(getContext(), this, bsItems, isGrid);
}
return adapter;
}
public void showItem(int itemId, boolean visible) {
if (visible) {
showItem(itemId);
} else {
hideItem(itemId);
}
}
public void showItem(int itemId) {
getAdapter().showItem(itemId);
// If we're not showing we don't want to animate.
if (!isShowing()) getAdapter().notifyDataSetChanged();
invalidateDialogLayout();
}
public void hideItem(int itemId) {
getAdapter().hideItem(itemId);
if (list == null) return;
if (isShowing()) {
// If we're not showing we don't want to animate.
getAdapter().notifyDataSetChanged();
invalidateDialogLayout();
return;
}
list.post(new Runnable() {
@Override
public void run() {
if (list == null) return;
list.getItemAnimator().isRunning(new ItemAnimatorFinishedListener() {
@Override
public void onAnimationsFinished() {
invalidateDialogLayout();
}
});
}
});
}
public boolean isItemVisible(int itemId) {
return getAdapter().isItemVisible(itemId);
}
public void postInvalidateDialogLayout() {
if (list == null) return;
list.post(new Runnable() {
@Override
public void run() {
invalidateDialogLayout();
}
});
}
public void invalidateDialogLayout() {
if (list == null) return;
int height = isGrid ? getGridHeight() : getListHeight();
list.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, height));
}
private int getGridHeight() {
Resources res = getContext().getResources();
int columnCount = res.getInteger(R.integer.bs_grid_colum);
int rowCount = (int) Math.ceil((float) getAdapter().getItemCountWithoutDividers() / columnCount);
return rowCount * itemHeight;
}
private int getListHeight() {
Resources res = getContext().getResources();
int itemCount = getAdapter().getItemCountWithoutDividers();
int dividerCount = getAdapter().getDividerCount();
int dividerHeight = res.getDimensionPixelSize(R.dimen.bs_divider_height)
+ res.getDimensionPixelSize(R.dimen.bs_divider_margin_top)
+ res.getDimensionPixelSize(R.dimen.bs_divider_margin_bottom);
return (itemCount * itemHeight) + (dividerCount * dividerHeight);
}
public void dismissAfterRipple() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
dismiss();
}
}, RIPPLE_ANIM_LENGTH);
}
public void hideAfterRipple() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
hide();
}
}, RIPPLE_ANIM_LENGTH);
}
/***
* Constructor using a activity for this builder and the {@link com.cocosw.bottomsheet.BottomSheet} it creates.
*/
public static class Builder {
private final Activity activity;
private int theme;
private final List<BSItem> bsItems = new ArrayList<>();
private CharSequence title;
private boolean isGrid;
private OnClickListener listener;
/**
* Constructor using a activity for this builder and the {@link com.cocosw.bottomsheet.BottomSheet} it creates.
*
* @param activity A Context for built BottomSheet.
*/
public Builder(@NonNull Activity activity) {
this(activity, R.style.BottomSheet_Dialog);
TypedArray ta = activity.getTheme().obtainStyledAttributes(new int[]{R.attr.bottomSheetStyle});
try {
theme = ta.getResourceId(0, R.style.BottomSheet_Dialog);
} finally {
ta.recycle();
}
}
/**
* Constructor using a activity for this builder and the {@link com.cocosw.bottomsheet.BottomSheet} it creates with given style
*
* @param activity An Activity for built BottomSheet.
*/
public Builder(Activity activity, @StyleRes int theme) {
this.activity = activity;
this.theme = theme;
}
/**
* Set menu resources as list item to display in BottomSheet
*
* @param xmlRes menu resource id
* @return This Builder object to allow for chaining of calls to set methods
*/
public Builder sheet(@MenuRes int xmlRes) {
bsItems.addAll(BSItem.parseMenuXml(activity, xmlRes));
return this;
}
@SuppressWarnings("UnusedReturnValue")
private Builder addItem(@NonNull BSItem item) {
bsItems.add(item);
return this;
}
/**
* Add one item into BottomSheet
*
* @param id ID of item
* @param iconRes icon resource
* @param textRes text resource
* @return This Builder object to allow for chaining of calls to set methods
*/
public Builder sheet(int id, @DrawableRes int iconRes, @StringRes int textRes) {
addItem(new BSItem(id, activity.getText(textRes), activity.getResources().getDrawable(iconRes)));
return this;
}
/**
* Add one item into BottomSheet
*
* @param id ID of item
* @param icon icon
* @param text text
* @return This Builder object to allow for chaining of calls to set methods
*/
public Builder sheet(int id,@NonNull Drawable icon, @NonNull CharSequence text) {
addItem(new BSItem(id, text, icon));
return this;
}
/**
* Add one item without icon into BottomSheet
*
* @param id ID of item
* @param textRes text resource
* @return This Builder object to allow for chaining of calls to set methods
*/
public Builder sheet(int id, @StringRes int textRes) {
addItem(new BSItem(id, activity.getText(textRes), null));
return this;
}
/**
* Add one item without icon into BottomSheet
*
* @param id ID of item
* @param text text
* @return This Builder object to allow for chaining of calls to set methods
*/
public Builder sheet(int id,@NonNull CharSequence text) {
addItem(new BSItem(id, text, null));
return this;
}
/**
* Set title for BottomSheet
* @param titleRes title for BottomSheet
* @return This Builder object to allow for chaining of calls to set methods
*/
public Builder title(@StringRes int titleRes) {
title = activity.getText(titleRes);
return this;
}
/**
* Add a divider in to the list
*
* @return This Builder object to allow for chaining of calls to set methods
*/
public Builder divider() {
BSItem item = new BSItem();
item.setIsDivider(true);
addItem(item);
return this;
}
/**
* Set OnclickListener for BottomSheet
*
* @param listener OnclickListener for BottomSheet
* @return This Builder object to allow for chaining of calls to set methods
*/
public Builder listener(@NonNull OnClickListener listener) {
this.listener = listener;
return this;
}
/**
* Show BottomSheet in dark color theme looking
* @return This Builder object to allow for chaining of calls to set methods
*/
public Builder darkTheme() {
theme = R.style.BottomSheet_Dialog_Dark;
return this;
}
/**
* Show BottomSheet
* @return This Builder object to allow for chaining of calls to set methods
*/
public BottomSheet show() {
BottomSheet dialog = create();
dialog.show();
return dialog;
}
/**
* Show items in grid instead of list
*
* @return This Builder object to allow for chaining of calls to set methods
*/
public Builder grid() {
this.isGrid = true;
return this;
}
/**
* Create a BottomSheet but not show it
* @return This Builder object to allow for chaining of calls to set methods
*/
@SuppressLint("Override")
public BottomSheet create() {
BottomSheet dialog = new BottomSheet(this);
return dialog;
}
/**
* Set title for BottomSheet
*
* @param title title for BottomSheet
* @return This Builder object to allow for chaining of calls to set methods
*/
public Builder title(CharSequence title) {
this.title = title;
return this;
}
}
}