Skip to content

Instantly share code, notes, and snippets.

@ianhanniballake
Last active July 18, 2019 16:28
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ianhanniballake/c33de76fcb255b7d7920 to your computer and use it in GitHub Desktop.
Save ianhanniballake/c33de76fcb255b7d7920 to your computer and use it in GitHub Desktop.
/*
* Copyright 2015 Google Inc.
*
* 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 com.example.behaviors;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.design.widget.CoordinatorLayout;
import android.util.AttributeSet;
import android.view.ViewGroup;
import static android.view.View.MeasureSpec;
/**
* Behavior that imposes a maximum width on any ViewGroup.
*
* <p />Requires an attrs.xml of something like
*
* <pre>
* &lt;declare-styleable name="MaxWidthBehavior_Params"&gt;
* &lt;attr name="behavior_maxWidth" format="dimension"/&gt;
* &lt;/declare-styleable&gt;
* </pre>
*/
public class MaxWidthBehavior<V extends ViewGroup> extends CoordinatorLayout.Behavior<V> {
private int mMaxWidth;
public MaxWidthBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.MaxWidthBehavior_Params);
mMaxWidth = a.getDimensionPixelSize(
R.styleable.MaxWidthBehavior_Params_behavior_maxWidth, 0);
a.recycle();
}
@Override
public boolean onMeasureChild(CoordinatorLayout parent, V child,
int parentWidthMeasureSpec, int widthUsed,
int parentHeightMeasureSpec, int heightUsed) {
if (mMaxWidth <= 0) {
// No max width means this Behavior is a no-op
return false;
}
int widthMode = MeasureSpec.getMode(parentWidthMeasureSpec);
int width = MeasureSpec.getSize(parentWidthMeasureSpec);
if (widthMode == MeasureSpec.UNSPECIFIED || width > mMaxWidth) {
// Sorry to impose here, but max width is kind of a big deal
width = mMaxWidth;
widthMode = MeasureSpec.AT_MOST;
parent.onMeasureChild(child,
MeasureSpec.makeMeasureSpec(width, widthMode), widthUsed,
parentHeightMeasureSpec, heightUsed);
// We've measured the View, so CoordinatorLayout doesn't have to
return true;
}
// Looks like the default measurement will work great
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment