下面列出了android.view.Gravity#TOP 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Sets all the required fields for the list view. Override this method to
* set a different list view behavior.
*/
protected void setUpRecyclerView() {
setVerticalScrollBarEnabled(false);
setFadingEdgeLength(0);
int gravity = mController.getScrollOrientation() == DatePickerDialog.ScrollOrientation.VERTICAL
? Gravity.TOP
: Gravity.START;
GravitySnapHelper helper = new GravitySnapHelper(gravity, new GravitySnapHelper.SnapListener() {
@Override
public void onSnap(int position) {
// Leverage the fact that the SnapHelper figures out which position is shown and
// pass this on to our PageListener after the snap has happened
if (pageListener != null) pageListener.onPageChanged(position);
}
});
helper.attachToRecyclerView(this);
}
/**
* Describes how the foreground is positioned. Defaults to START and TOP.
*
* @param foregroundGravity See {@link android.view.Gravity}
* @see #getForegroundGravity()
*/
public void setForegroundGravity(int foregroundGravity) {
if (mForegroundGravity != foregroundGravity) {
if ((foregroundGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) {
foregroundGravity |= Gravity.START;
}
if ((foregroundGravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
foregroundGravity |= Gravity.TOP;
}
mForegroundGravity = foregroundGravity;
if (mForegroundGravity == Gravity.FILL && mForeground != null) {
Rect padding = new Rect();
mForeground.getPadding(padding);
}
requestLayout();
}
}
private void applyTranslationToTopChildViews(ViewGroup contentView, float translation) {
for (int i = 0; i < contentView.getChildCount(); i++) {
View child = contentView.getChildAt(i);
if (!(child.getLayoutParams() instanceof FrameLayout.LayoutParams)) continue;
FrameLayout.LayoutParams layoutParams =
(FrameLayout.LayoutParams) child.getLayoutParams();
if (Gravity.TOP == (layoutParams.gravity & Gravity.FILL_VERTICAL)) {
child.setTranslationY(translation);
TraceEvent.instant("FullscreenManager:child.setTranslationY()");
}
}
}
public void show() {
View anchor = context.getWindow().getDecorView().getRootView();
setContentView(new DebugLayout(context, anchor));
getContentView().setLayoutParams(new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
setBackgroundDrawable(new ColorDrawable(context.getResources().getColor(android.R.color.transparent)));
setTouchable(false);
setFocusable(false);
setOutsideTouchable(false);
setAnimationStyle(0);
super.showAtLocation(anchor, Gravity.START | Gravity.TOP, 0, 0);
update(anchor.getWidth(), anchor.getHeight());
anchor.getViewTreeObserver().addOnPreDrawListener(listener);
}
private void initHeaderToastView() {
wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
//为mHeaderToastView添加parent使其能够展示动画效果
linearLayout = new LinearLayout(mContext);
LinearLayout.LayoutParams llParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
linearLayout.setLayoutParams(llParams);
mHeaderToastView = View.inflate(mContext, R.layout.header_toast, null);
//为mHeaderToastView添加滑动删除事件
mHeaderToastView.setOnTouchListener(this);
iv_header_toast = (ImageView) mHeaderToastView.findViewById(R.id.iv_header_toast);
tv_header_toast = (TextView) mHeaderToastView.findViewById(R.id.tv_header_toast);
WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
wmParams.width = WindowManager.LayoutParams.MATCH_PARENT;
wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
wmParams.gravity = Gravity.CENTER | Gravity.TOP;
wmParams.x = 0;
wmParams.y = 0;
wmParams.format = PixelFormat.TRANSLUCENT;
wmParams.type = WindowManager.LayoutParams.TYPE_TOAST;
linearLayout.addView(mHeaderToastView);
wm.addView(linearLayout, wmParams);
}
private void setupStatusBarView(Context context, ViewGroup decorViewGroup) {
mStatusBarTintView = new View(context);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getStatusBarHeight());
params.gravity = Gravity.TOP;
if (mNavBarAvailable && !mConfig.isNavigationAtBottom()) {
params.rightMargin = mConfig.getNavigationBarWidth();
}
mStatusBarTintView.setLayoutParams(params);
mStatusBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR);
mStatusBarTintView.setVisibility(View.GONE);
decorViewGroup.addView(mStatusBarTintView);
}
private void createFloatView() {
wmParams = Util.getParams(wmParams);
// 悬浮窗默认显示以左上角为起始坐标
wmParams.gravity = Gravity.RIGHT| Gravity.TOP;
if (!prefs.isRightMode()) {
wmParams.gravity = Gravity.LEFT | Gravity.TOP;
}
// 以屏幕右上角为原点,设置x、y初始值,确定显示窗口的起始位置
wmParams.x = 0;
wmParams.y = 0;
mWindowManager = (WindowManager) service.getSystemService(Context.WINDOW_SERVICE);
LayoutInflater inflater = LayoutInflater.from(service);
// 获取浮动窗口视图所在布局
mFloatLayout = (LinearLayout) inflater.inflate(R.layout.floating, null);
// 添加悬浮窗的视图
mWindowManager.addView(mFloatLayout, wmParams);
/**
* 设置悬浮窗的点击、滑动事件
*/
sampleFloat = (ImageButton) mFloatLayout.findViewById(R.id.float_button_id);
sampleFloat.getBackground().setAlpha(150);
sampleFloat.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
prefs.doTouch(service);
}
});
/**
* 设置有无反馈
*/
MyOnGestureListener listener = new MyOnGestureListener();
@SuppressWarnings("deprecation")
final GestureDetector mGestureDetector = new GestureDetector(listener);
sampleFloat.setOnTouchListener(new MyOnTouchListener(mGestureDetector));
}
@OnClick(R.id.settings_caption)
public void openSettingsDialog() {
ActivityUtils.get(this).hideSoftKeyboard();
_dialogView = View.inflate(this, R.layout.ui__memecreate__text_settings, null);
initTextSettingsPopupDialog(_dialogView);
AlertDialog dialog = new AlertDialog.Builder(this).setTitle(R.string.settings)
//dialog _dialogView
.setView(_dialogView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//retrieve values of widgets
//return focus to _create_caption
_create_caption.requestFocus();
}
})
.setOnDismissListener((di) -> {
_toolbar.setVisibility(View.VISIBLE);
_imageEditView.setPadding(0, 0, 0, 0);
})
.create();
// Get some more space
try {
_toolbar.setVisibility(View.GONE);
WindowManager.LayoutParams wmlp = dialog.getWindow().getAttributes();
wmlp.gravity = Gravity.TOP;
android.graphics.Point p = new android.graphics.Point();
getWindowManager().getDefaultDisplay().getSize(p);
_imageEditView.setPadding(0, p.y / 2, 0, 0);
} catch (Exception ignored) {
}
dialog.show();
}
private void setupStatusBarView(Context context, ViewGroup decorViewGroup) {
mStatusBarTintView = new View(context);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getStatusBarHeight());
params.gravity = Gravity.TOP;
if (mNavBarAvailable && !mConfig.isNavigationAtBottom()) {
params.rightMargin = mConfig.getNavigationBarWidth();
}
mStatusBarTintView.setLayoutParams(params);
mStatusBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR);
mStatusBarTintView.setVisibility(View.GONE);
decorViewGroup.addView(mStatusBarTintView);
}
void updateTextPositions(int position, float positionOffset, boolean force) {
if (position != mLastKnownCurrentPage) {
updateText(position, mPager.getAdapter());
} else if (!force && positionOffset == mLastKnownPositionOffset) {
return;
}
mUpdatingPositions = true;
final int prevWidth = mPrevText.getMeasuredWidth();
final int currWidth = mCurrText.getMeasuredWidth();
final int nextWidth = mNextText.getMeasuredWidth();
final int halfCurrWidth = currWidth / 2;
final int stripWidth = getWidth();
final int stripHeight = getHeight();
final int paddingLeft = getPaddingLeft();
final int paddingRight = getPaddingRight();
final int paddingTop = getPaddingTop();
final int paddingBottom = getPaddingBottom();
final int textPaddedLeft = paddingLeft + halfCurrWidth;
final int textPaddedRight = paddingRight + halfCurrWidth;
final int contentWidth = stripWidth - textPaddedLeft - textPaddedRight;
float currOffset = positionOffset + 0.5f;
if (currOffset > 1.f) {
currOffset -= 1.f;
}
final int currCenter = stripWidth - textPaddedRight - (int) (contentWidth * currOffset);
final int currLeft = currCenter - currWidth / 2;
final int currRight = currLeft + currWidth;
final int prevBaseline = mPrevText.getBaseline();
final int currBaseline = mCurrText.getBaseline();
final int nextBaseline = mNextText.getBaseline();
final int maxBaseline = Math.max(Math.max(prevBaseline, currBaseline), nextBaseline);
final int prevTopOffset = maxBaseline - prevBaseline;
final int currTopOffset = maxBaseline - currBaseline;
final int nextTopOffset = maxBaseline - nextBaseline;
final int alignedPrevHeight = prevTopOffset + mPrevText.getMeasuredHeight();
final int alignedCurrHeight = currTopOffset + mCurrText.getMeasuredHeight();
final int alignedNextHeight = nextTopOffset + mNextText.getMeasuredHeight();
final int maxTextHeight = Math.max(Math.max(alignedPrevHeight, alignedCurrHeight),
alignedNextHeight);
final int vgrav = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
int prevTop;
int currTop;
int nextTop;
switch (vgrav) {
default:
case Gravity.TOP:
prevTop = paddingTop + prevTopOffset;
currTop = paddingTop + currTopOffset;
nextTop = paddingTop + nextTopOffset;
break;
case Gravity.CENTER_VERTICAL:
final int paddedHeight = stripHeight - paddingTop - paddingBottom;
final int centeredTop = (paddedHeight - maxTextHeight) / 2;
prevTop = centeredTop + prevTopOffset;
currTop = centeredTop + currTopOffset;
nextTop = centeredTop + nextTopOffset;
break;
case Gravity.BOTTOM:
final int bottomGravTop = stripHeight - paddingBottom - maxTextHeight;
prevTop = bottomGravTop + prevTopOffset;
currTop = bottomGravTop + currTopOffset;
nextTop = bottomGravTop + nextTopOffset;
break;
}
mCurrText.layout(currLeft, currTop, currRight,
currTop + mCurrText.getMeasuredHeight());
final int prevLeft = Math.min(paddingLeft, currLeft - mScaledTextSpacing - prevWidth);
mPrevText.layout(prevLeft, prevTop, prevLeft + prevWidth,
prevTop + mPrevText.getMeasuredHeight());
final int nextLeft = Math.max(stripWidth - paddingRight - nextWidth,
currRight + mScaledTextSpacing);
mNextText.layout(nextLeft, nextTop, nextLeft + nextWidth,
nextTop + mNextText.getMeasuredHeight());
mLastKnownPositionOffset = positionOffset;
mUpdatingPositions = false;
}
private void reuseSavedWindowMangerPosition(int width_vale, int height_value) {
//获取windowManager
int w = width_vale;
int h = height_value;
if (layoutParams == null) {
DisplayMetrics displayMetrics = new DisplayMetrics();
mWindowManager.getDefaultDisplay().getMetrics(displayMetrics);
density = displayMetrics.density;
int flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
int type = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Settings.canDrawOverlays(mContext)) {
type = WindowManager.LayoutParams.TYPE_PHONE;
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
type = WindowManager.LayoutParams.TYPE_TOAST;
} else {
type = WindowManager.LayoutParams.TYPE_PHONE;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
Point point = new Point();
mWindowManager.getDefaultDisplay().getSize(point);
mScreenWidth = point.x;
mScreenHeight = point.y;
} else {
mScreenWidth = mWindowManager.getDefaultDisplay().getWidth();
mScreenHeight = mWindowManager.getDefaultDisplay().getHeight();
}
rotation = mWindowManager.getDefaultDisplay().getRotation();
int x = 0, y = 0;
if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) {
x = SPHelper.getInt(Constants.FLOAT_VIEW_PORT_X, mScreenWidth);
y = SPHelper.getInt(Constants.FLOAT_VIEW_PORT_Y, mScreenHeight / 2);
} else {
x = SPHelper.getInt(Constants.FLOAT_VIEW_LAND_X, mScreenWidth);
y = SPHelper.getInt(Constants.FLOAT_VIEW_LAND_Y, mScreenHeight / 2);
}
layoutParams = new WindowManager.LayoutParams(w, h, type, flags, PixelFormat.TRANSLUCENT);
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams.x = x;
layoutParams.y = y;
} else {
layoutParams.width = w;
layoutParams.height = h;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar);
setContentView(R.layout.device_list);
android.view.WindowManager.LayoutParams layoutParams = this.getWindow().getAttributes();
layoutParams.gravity=Gravity.TOP;
layoutParams.y = 200;
mHandler = new Handler();
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
return;
}
populateList();
mEmptyList = (TextView) findViewById(R.id.empty);
Button cancelButton = (Button) findViewById(R.id.btn_cancel);
cancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mScanning==false) scanLeDevice(true);
else finish();
}
});
}
public LayoutParams(android.widget.FrameLayout.LayoutParams source) {
super((MarginLayoutParams) source);
if (gravity == 0)
gravity = GravityCompat.START | Gravity.TOP;
}
private void initBadge() {
mBadgeView = TabBadgeView.bindTab(this);
if (mTabBadge.getBackgroundColor() != 0xFFE84E40) {
mBadgeView.setBadgeBackgroundColor(mTabBadge.getBackgroundColor());
}
if (mTabBadge.getBadgeTextColor() != 0xFFFFFFFF) {
mBadgeView.setBadgeTextColor(mTabBadge.getBadgeTextColor());
}
if (mTabBadge.getStrokeColor() != Color.TRANSPARENT || mTabBadge.getStrokeWidth() != 0) {
mBadgeView.stroke(mTabBadge.getStrokeColor(), mTabBadge.getStrokeWidth(), true);
}
if (mTabBadge.getDrawableBackground() != null || mTabBadge.isDrawableBackgroundClip()) {
mBadgeView.setBadgeBackground(mTabBadge.getDrawableBackground(), mTabBadge.isDrawableBackgroundClip());
}
if (mTabBadge.getBadgeTextSize() != 11) {
mBadgeView.setBadgeTextSize(mTabBadge.getBadgeTextSize(), true);
}
if (mTabBadge.getBadgePadding() != 5) {
mBadgeView.setBadgePadding(mTabBadge.getBadgePadding(), true);
}
if (mTabBadge.getBadgeNumber() != 0) {
mBadgeView.setBadgeNumber(mTabBadge.getBadgeNumber());
}
if (mTabBadge.getBadgeText() != null) {
mBadgeView.setBadgeText(mTabBadge.getBadgeText());
}
if (mTabBadge.getBadgeGravity() != (Gravity.END | Gravity.TOP)) {
mBadgeView.setBadgeGravity(mTabBadge.getBadgeGravity());
}
if (mTabBadge.getGravityOffsetX() != 5 || mTabBadge.getGravityOffsetY() != 5) {
mBadgeView.setGravityOffset(mTabBadge.getGravityOffsetX(), mTabBadge.getGravityOffsetY(), true);
}
if (mTabBadge.isExactMode()) {
mBadgeView.setExactMode(mTabBadge.isExactMode());
}
if (!mTabBadge.isShowShadow()) {
mBadgeView.setShowShadow(mTabBadge.isShowShadow());
}
if (mTabBadge.getOnDragStateChangedListener() != null) {
mBadgeView.setOnDragStateChangedListener(mTabBadge.getOnDragStateChangedListener());
}
}
/**
* 更新悬浮窗布局等
*/
private void updateUi() {
RIGHT_MODE = !prefs.getDrawMode();
DRAW_COLOR = prefs.getDrawColor();
ALPHA = prefs.getDrawAlpha();
// 获取浮动窗口视图所在布局
layout = (LinearLayout) inflater.inflate(RIGHT_MODE ? R.layout.draw_right : R.layout.draw_left, null);
// 添加悬浮窗的视图
mWindowManager.addView(layout, wmParams);
/**
* 设置抽屉控件的打开方向和监听器
*/
mDrawerLayout = (DrawerLayout) layout.findViewById(R.id.drawer_layout);
mDrawerLayout.setDrawerListener(new MyDrawListener());
mDrawerLayout.openDrawer(RIGHT_MODE ? Gravity.RIGHT : Gravity.LEFT);
/**
* 设置上方的home键
*/
Button home = (Button) layout.findViewById(R.id.home_key);
home.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Util.virtualHome(getBaseContext());
stopSelf();
}
});
/**
* 设置抽屉控件内的背景
*/
drawContent = (LinearLayout) layout.findViewById(R.id.drawer_content);
drawContent.setBackgroundColor(DRAW_COLOR);
drawContent.getBackground().setAlpha(ALPHA);
/**
* 设置最近任务list中item的个数:20
*/
Util.reloadButtons(this, appInfos, 20);
ListView listView = (ListView) layout.findViewById(R.id.drawer_list);
listView.setAdapter(new AppAdapter(this, mWindowManager, layout, mDrawerLayout, appInfos));
// 悬浮窗显示确定右上角为起始坐标
wmParams.gravity = RIGHT_MODE ? Gravity.RIGHT : Gravity.LEFT | Gravity.TOP;
// 以屏幕右上角为原点,设置x、y初始值,确定显示窗口的起始位置
// 添加动画。参考自:http://bbs.9ria.com/thread-242912-1-1.html
wmParams.windowAnimations = (RIGHT_MODE) ? R.style.right_anim : R.style.left_anim;
mWindowManager.updateViewLayout(layout, wmParams);
}
public static void setupItem(MaterialAboutActionItemViewHolder holder, MaterialAboutActionItem item, Context context) {
CharSequence text = item.getText();
int textRes = item.getTextRes();
holder.text.setVisibility(View.VISIBLE);
if (text != null) {
holder.text.setText(text);
} else if (textRes != 0) {
holder.text.setText(textRes);
} else {
holder.text.setVisibility(GONE);
}
CharSequence subText = item.getSubText();
int subTextRes = item.getSubTextRes();
holder.subText.setVisibility(View.VISIBLE);
if (subText != null) {
holder.subText.setText(subText);
} else if (subTextRes != 0) {
holder.subText.setText(subTextRes);
} else {
holder.subText.setVisibility(GONE);
}
if (item.shouldShowIcon()) {
holder.icon.setVisibility(View.VISIBLE);
Drawable drawable = item.getIcon();
int drawableRes = item.getIconRes();
if (drawable != null) {
holder.icon.setImageDrawable(drawable);
} else if (drawableRes != 0) {
holder.icon.setImageResource(drawableRes);
}
} else {
holder.icon.setVisibility(GONE);
}
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) holder.icon.getLayoutParams();
switch (item.getIconGravity()) {
case MaterialAboutActionItem.GRAVITY_TOP:
params.gravity = Gravity.TOP;
break;
case MaterialAboutActionItem.GRAVITY_MIDDLE:
params.gravity = Gravity.CENTER_VERTICAL;
break;
case MaterialAboutActionItem.GRAVITY_BOTTOM:
params.gravity = Gravity.BOTTOM;
break;
}
holder.icon.setLayoutParams(params);
int pL = 0, pT = 0, pR = 0, pB = 0;
if (Build.VERSION.SDK_INT < 21) {
pL = holder.view.getPaddingLeft();
pT = holder.view.getPaddingTop();
pR = holder.view.getPaddingRight();
pB = holder.view.getPaddingBottom();
}
if (item.getOnClickAction() != null || item.getOnLongClickAction() != null) {
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(R.attr.selectableItemBackground, outValue, true);
holder.view.setBackgroundResource(outValue.resourceId);
} else {
holder.view.setBackgroundResource(0);
}
holder.setOnClickAction(item.getOnClickAction());
holder.setOnLongClickAction(item.getOnLongClickAction());
if (Build.VERSION.SDK_INT < 21) {
holder.view.setPadding(pL, pT, pR, pB);
}
}
@SuppressLint("RtlHardcoded")
private boolean layoutLocationBar(int containerWidth) {
// Note that Toolbar's direction depends on system layout direction while
// LocationBar's direction depends on its text inside.
FrameLayout.LayoutParams locationBarLayoutParams =
getFrameLayoutParams(getLocationBar().getContainerView());
// Chrome prevents layout_gravity="left" from being defined in XML, but it simplifies
// the logic, so it is manually specified here.
locationBarLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
int width = 0;
int leftMargin = 0;
// Always update the unfocused layout params regardless of whether we are using
// those in this current layout pass as they are needed for animations.
updateUnfocusedLocationBarLayoutParams();
if (mLayoutLocationBarInFocusedMode || mVisualState == VisualState.NEW_TAB_NORMAL) {
int priorVisibleWidth = 0;
for (int i = 0; i < mLocationBar.getChildCount(); i++) {
View child = mLocationBar.getChildAt(i);
if (child == mLocationBar.getFirstViewVisibleWhenFocused()) break;
if (child.getVisibility() == GONE) continue;
priorVisibleWidth += child.getMeasuredWidth();
}
width = containerWidth - (2 * mToolbarSidePadding) + priorVisibleWidth;
if (ApiCompatibilityUtils.isLayoutRtl(mLocationBar)) {
leftMargin = mToolbarSidePadding;
} else {
leftMargin = -priorVisibleWidth + mToolbarSidePadding;
}
} else {
width = mUnfocusedLocationBarLayoutWidth;
leftMargin = mUnfocusedLocationBarLayoutLeft;
}
boolean changed = false;
changed |= (width != locationBarLayoutParams.width);
locationBarLayoutParams.width = width;
changed |= (leftMargin != locationBarLayoutParams.leftMargin);
locationBarLayoutParams.leftMargin = leftMargin;
return changed;
}
public GravitySnapRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs,
R.styleable.GravitySnapRecyclerView, defStyleAttr, 0);
int snapGravity = typedArray.getInt(
R.styleable.GravitySnapRecyclerView_snapGravity, 0);
switch (snapGravity) {
case 0:
snapHelper = new GravitySnapHelper(Gravity.START);
break;
case 1:
snapHelper = new GravitySnapHelper(Gravity.TOP);
break;
case 2:
snapHelper = new GravitySnapHelper(Gravity.END);
break;
case 3:
snapHelper = new GravitySnapHelper(Gravity.BOTTOM);
break;
case 4:
snapHelper = new GravitySnapHelper(Gravity.CENTER);
break;
default:
throw new IllegalArgumentException("Invalid gravity value. Use START " +
"| END | BOTTOM | TOP | CENTER constants");
}
snapHelper.setSnapToPadding(typedArray.getBoolean(
R.styleable.GravitySnapRecyclerView_snapToPadding, false));
snapHelper.setSnapLastItem(typedArray.getBoolean(
R.styleable.GravitySnapRecyclerView_snapLastItem, false));
snapHelper.setMaxFlingSizeFraction(typedArray.getFloat(
R.styleable.GravitySnapRecyclerView_snapMaxFlingSizeFraction,
GravitySnapHelper.FLING_SIZE_FRACTION_DISABLE));
snapHelper.setScrollMsPerInch(typedArray.getFloat(
R.styleable.GravitySnapRecyclerView_snapScrollMsPerInch, 100f));
enableSnapping(typedArray.getBoolean(
R.styleable.GravitySnapRecyclerView_snapEnabled, true));
typedArray.recycle();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
//Inflate the layout using LayoutInflater
LayoutInflater li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
floatingControls = (LinearLayout) li.inflate(R.layout.layout_floating_controls, null);
controls = floatingControls.findViewById(R.id.controls);
//Initialize imageButtons
ImageButton stopIB = controls.findViewById(R.id.stop);
pauseIB = controls.findViewById(R.id.pause);
resumeIB = controls.findViewById(R.id.resume);
resumeIB.setEnabled(false);
stopIB.setOnClickListener(this);
//Get floating control icon size from sharedpreference
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
//Pause/Resume doesnt work below SDK version 24. Remove them
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
pauseIB.setVisibility(View.GONE);
resumeIB.setVisibility(View.GONE);
controls.findViewById(R.id.divider1).setVisibility(View.GONE);
controls.findViewById(R.id.divider2).setVisibility(View.GONE);
} else {
pauseIB.setOnClickListener(this);
resumeIB.setOnClickListener(this);
}
//Set layout params to display the controls over any screen.
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
dpToPx(pref.getInt(getString(R.string.preference_floating_control_size_key), 100)),
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
// From API26, TYPE_PHONE depricated. Use TYPE_APPLICATION_OVERLAY for O
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
params.type = WindowManager.LayoutParams.TYPE_PHONE;
//Initial position of the floating controls
params.gravity = Gravity.TOP | Gravity.START;
params.x = 0;
params.y = 100;
//Add the controls view to windowmanager
windowManager.addView(floatingControls, params);
//Add touch listerner to floating controls view to move/close/expand the controls
try {
floatingControls.setOnTouchListener(new View.OnTouchListener() {
boolean isMoving = false;
private WindowManager.LayoutParams paramsF = params;
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
isMoving = false;
initialX = paramsF.x;
initialY = paramsF.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
break;
case MotionEvent.ACTION_UP:
if (!isMoving) {
if (controls.getVisibility() == View.INVISIBLE) {
expandFloatingControls();
} else {
collapseFloatingControls();
}
}
break;
case MotionEvent.ACTION_MOVE:
int xDiff = (int) (event.getRawX() - initialTouchX);
int yDiff = (int) (event.getRawY() - initialTouchY);
paramsF.x = initialX + xDiff;
paramsF.y = initialY + yDiff;
/* Set an offset of 10 pixels to determine controls moving. Else, normal touches
* could react as moving the control window around */
if (Math.abs(xDiff) > 10 || Math.abs(yDiff) > 10)
isMoving = true;
windowManager.updateViewLayout(floatingControls, paramsF);
break;
}
return false;
}
});
} catch (Exception e) {
// TODO: handle exception
}
return START_STICKY;
}
private FloatingActionButton createFab(Context context, int buttonDrawable, int buttonColor, int buttonPosition) {
fab = new TintFloatingActionButton(context);
int fabElevationInPixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics());
LayoutParams fabLayoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
fabMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics());
if (buttonPosition == RIGHT) {
fabLayoutParams.gravity = Gravity.END | Gravity.TOP;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
fabLayoutParams.setMarginEnd(fabMargin);
} else {
fabLayoutParams.rightMargin = fabMargin;
}
} else if (buttonPosition == CENTER) {
fabLayoutParams.gravity = Gravity.CENTER | Gravity.TOP;
} else {
fabLayoutParams.gravity = Gravity.START | Gravity.TOP;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
fabLayoutParams.setMarginStart(fabMargin);
} else {
fabLayoutParams.leftMargin = fabMargin;
}
}
fabLayoutParams.bottomMargin = fabMargin;
fabLayoutParams.topMargin = fabMargin;
if (buttonDrawable > 0) {
fab.setImageDrawable(ContextCompat.getDrawable(context, buttonDrawable));
}
if (buttonColor > 0) {
ViewCompat.setBackgroundTintList(fab, ContextCompat.getColorStateList(context, buttonColor));
}
ViewCompat.setElevation(fab, fabElevationInPixels);
fab.setLayoutParams(fabLayoutParams);
fab.setTag("FAB");
this.addView(fab);
return fab;
}