Java Code Examples for com.google.android.material.internal.ThemeEnforcement#obtainStyledAttributes()

The following examples show how to use com.google.android.material.internal.ThemeEnforcement#obtainStyledAttributes() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SwitchMaterial.java    From material-components-android with Apache License 2.0 6 votes vote down vote up
public SwitchMaterial(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  super(wrap(context, attrs, defStyleAttr, DEF_STYLE_RES), attrs, defStyleAttr);
  // Ensure we are using the correctly themed context rather than the context that was passed in.
  context = getContext();

  elevationOverlayProvider = new ElevationOverlayProvider(context);

  TypedArray attributes =
      ThemeEnforcement.obtainStyledAttributes(
          context, attrs, R.styleable.SwitchMaterial, defStyleAttr, DEF_STYLE_RES);

  useMaterialThemeColors =
      attributes.getBoolean(R.styleable.SwitchMaterial_useMaterialThemeColors, false);

  attributes.recycle();
}
 
Example 2
Source File: MaterialRadioButton.java    From material-components-android with Apache License 2.0 6 votes vote down vote up
public MaterialRadioButton(
    @NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  super(wrap(context, attrs, defStyleAttr, DEF_STYLE_RES), attrs, defStyleAttr);
  // Ensure we are using the correctly themed context rather than the context that was passed in.
  context = getContext();

  TypedArray attributes =
      ThemeEnforcement.obtainStyledAttributes(
          context, attrs, R.styleable.MaterialRadioButton, defStyleAttr, DEF_STYLE_RES);

  // If buttonTint is specified, read it using MaterialResources to allow themeable attributes in
  // all API levels.
  if (attributes.hasValue(R.styleable.MaterialRadioButton_buttonTint)) {
    CompoundButtonCompat.setButtonTintList(
        this,
        MaterialResources.getColorStateList(
            context, attributes, R.styleable.MaterialRadioButton_buttonTint));
  }

  useMaterialThemeColors =
      attributes.getBoolean(R.styleable.MaterialRadioButton_useMaterialThemeColors, false);

  attributes.recycle();
}
 
Example 3
Source File: Chip.java    From material-components-android with Apache License 2.0 6 votes vote down vote up
private void initMinTouchTarget(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  // Checks if the Chip should meet Android's minimum touch target size.
  TypedArray a =
      ThemeEnforcement.obtainStyledAttributes(
          context,
          attrs,
          R.styleable.Chip,
          defStyleAttr,
          DEF_STYLE_RES);
  ensureMinTouchTargetSize = a.getBoolean(R.styleable.Chip_ensureMinTouchTargetSize, false);

  float defaultMinTouchTargetSize =
      (float) Math.ceil(ViewUtils.dpToPx(getContext(), MIN_TOUCH_TARGET_DP));
  minTouchTargetSize =
      (int)
          Math.ceil(
              a.getDimension(R.styleable.Chip_chipMinTouchTargetSize, defaultMinTouchTargetSize));

  a.recycle();
}
 
Example 4
Source File: MaterialCheckBox.java    From material-components-android with Apache License 2.0 6 votes vote down vote up
public MaterialCheckBox(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  super(wrap(context, attrs, defStyleAttr, DEF_STYLE_RES), attrs, defStyleAttr);
  // Ensure we are using the correctly themed context rather than the context that was passed in.
  context = getContext();

  TypedArray attributes =
      ThemeEnforcement.obtainStyledAttributes(
          context, attrs, R.styleable.MaterialCheckBox, defStyleAttr, DEF_STYLE_RES);

  // If buttonTint is specified, read it using MaterialResources to allow themeable attributes in
  // all API levels.
  if (attributes.hasValue(R.styleable.MaterialCheckBox_buttonTint)) {
    CompoundButtonCompat.setButtonTintList(
        this,
        MaterialResources.getColorStateList(
            context, attributes, R.styleable.MaterialCheckBox_buttonTint));
  }

  useMaterialThemeColors =
      attributes.getBoolean(R.styleable.MaterialCheckBox_useMaterialThemeColors, false);

  attributes.recycle();
}
 
Example 5
Source File: MaterialButtonToggleGroup.java    From material-components-android with Apache License 2.0 6 votes vote down vote up
public MaterialButtonToggleGroup(
    @NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  super(wrap(context, attrs, defStyleAttr, DEF_STYLE_RES), attrs, defStyleAttr);
  // Ensure we are using the correctly themed context rather than the context that was passed in.
  context = getContext();
  TypedArray attributes =
      ThemeEnforcement.obtainStyledAttributes(
          context, attrs, R.styleable.MaterialButtonToggleGroup, defStyleAttr, DEF_STYLE_RES);

  setSingleSelection(
      attributes.getBoolean(R.styleable.MaterialButtonToggleGroup_singleSelection, false));
  checkedId =
      attributes.getResourceId(R.styleable.MaterialButtonToggleGroup_checkedButton, View.NO_ID);
  selectionRequired =
      attributes.getBoolean(R.styleable.MaterialButtonToggleGroup_selectionRequired, false);
  setChildrenDrawingOrderEnabled(true);
  attributes.recycle();

  ViewCompat.setImportantForAccessibility(this, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
 
Example 6
Source File: MaterialCardView.java    From material-components-android with Apache License 2.0 6 votes vote down vote up
public MaterialCardView(Context context, AttributeSet attrs, int defStyleAttr) {
  super(wrap(context, attrs, defStyleAttr, DEF_STYLE_RES), attrs, defStyleAttr);
  isParentCardViewDoneInitializing = true;
  // Ensure we are using the correctly themed context rather than the context that was passed in.
  context = getContext();

  TypedArray attributes =
      ThemeEnforcement.obtainStyledAttributes(
          context, attrs, R.styleable.MaterialCardView, defStyleAttr, DEF_STYLE_RES);

  // Loads and sets background drawable attributes.
  cardViewHelper = new MaterialCardViewHelper(this, attrs, defStyleAttr, DEF_STYLE_RES);
  cardViewHelper.setCardBackgroundColor(super.getCardBackgroundColor());
  cardViewHelper.setUserContentPadding(
      super.getContentPaddingLeft(),
      super.getContentPaddingTop(),
      super.getContentPaddingRight(),
      super.getContentPaddingBottom());
  // Zero out the AppCompat CardView's content padding, the padding will be added to the internal
  // contentLayout.
  cardViewHelper.loadFromAttributes(attributes);

  attributes.recycle();
}
 
Example 7
Source File: TextInputEditText.java    From material-components-android with Apache License 2.0 6 votes vote down vote up
public TextInputEditText(
    @NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  super(wrap(context, attrs, defStyleAttr, 0), attrs, defStyleAttr);
  TypedArray attributes =
      ThemeEnforcement.obtainStyledAttributes(
          context,
          attrs,
          R.styleable.TextInputEditText,
          defStyleAttr,
          R.style.Widget_Design_TextInputEditText);

  setTextInputLayoutFocusedRectEnabled(
      attributes.getBoolean(R.styleable.TextInputEditText_textInputLayoutFocusedRectEnabled, false));

  attributes.recycle();
}
 
Example 8
Source File: ViewUtilsLollipop.java    From material-components-android with Apache License 2.0 6 votes vote down vote up
static void setStateListAnimatorFromAttrs(
    @NonNull View view, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
  final Context context = view.getContext();
  final TypedArray a =
      ThemeEnforcement.obtainStyledAttributes(
          context, attrs, STATE_LIST_ANIM_ATTRS, defStyleAttr, defStyleRes);
  try {
    if (a.hasValue(0)) {
      StateListAnimator sla =
          AnimatorInflater.loadStateListAnimator(context, a.getResourceId(0, 0));
      view.setStateListAnimator(sla);
    }
  } finally {
    a.recycle();
  }
}
 
Example 9
Source File: BadgeDrawable.java    From material-components-android with Apache License 2.0 5 votes vote down vote up
private void loadDefaultStateFromAttributes(
    Context context, AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
  TypedArray a =
      ThemeEnforcement.obtainStyledAttributes(
          context, attrs, R.styleable.Badge, defStyleAttr, defStyleRes);

  setMaxCharacterCount(
      a.getInt(R.styleable.Badge_maxCharacterCount, DEFAULT_MAX_BADGE_CHARACTER_COUNT));

  // Only set the badge number if it exists in the style.
  // Defaulting it to 0 means the badge will incorrectly show text when the user may want a
  // numberless badge.
  if (a.hasValue(R.styleable.Badge_number)) {
    setNumber(a.getInt(R.styleable.Badge_number, 0));
  }

  setBackgroundColor(readColorFromAttributes(context, a, R.styleable.Badge_backgroundColor));

  // Only set the badge text color if this attribute has explicitly been set, otherwise use the
  // text color specified in the TextAppearance.
  if (a.hasValue(R.styleable.Badge_badgeTextColor)) {
    setBadgeTextColor(readColorFromAttributes(context, a, R.styleable.Badge_badgeTextColor));
  }

  setBadgeGravity(a.getInt(R.styleable.Badge_badgeGravity, TOP_END));

  setHorizontalOffset(a.getDimensionPixelOffset(R.styleable.Badge_horizontalOffset, 0));
  setVerticalOffset(a.getDimensionPixelOffset(R.styleable.Badge_verticalOffset, 0));

  a.recycle();
}
 
Example 10
Source File: MaterialButton.java    From material-components-android with Apache License 2.0 5 votes vote down vote up
public MaterialButton(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  super(wrap(context, attrs, defStyleAttr, DEF_STYLE_RES), attrs, defStyleAttr);
  // Ensure we are using the correctly themed context rather than the context that was passed in.
  context = getContext();

  TypedArray attributes =
      ThemeEnforcement.obtainStyledAttributes(
          context, attrs, R.styleable.MaterialButton, defStyleAttr, DEF_STYLE_RES);

  iconPadding = attributes.getDimensionPixelSize(R.styleable.MaterialButton_iconPadding, 0);
  iconTintMode =
      ViewUtils.parseTintMode(
          attributes.getInt(R.styleable.MaterialButton_iconTintMode, -1), Mode.SRC_IN);

  iconTint =
      MaterialResources.getColorStateList(
          getContext(), attributes, R.styleable.MaterialButton_iconTint);
  icon = MaterialResources.getDrawable(getContext(), attributes, R.styleable.MaterialButton_icon);
  iconGravity = attributes.getInteger(R.styleable.MaterialButton_iconGravity, ICON_GRAVITY_START);

  iconSize = attributes.getDimensionPixelSize(R.styleable.MaterialButton_iconSize, 0);
  ShapeAppearanceModel shapeAppearanceModel =
      ShapeAppearanceModel.builder(context, attrs, defStyleAttr, DEF_STYLE_RES).build();

  // Loads and sets background drawable attributes
  materialButtonHelper = new MaterialButtonHelper(this, shapeAppearanceModel);
  materialButtonHelper.loadFromAttributes(attributes);

  attributes.recycle();

  setCompoundDrawablePadding(iconPadding);
  updateIcon(/*needsIconReset=*/icon != null);
}
 
Example 11
Source File: MaterialAutoCompleteTextView.java    From material-components-android with Apache License 2.0 4 votes vote down vote up
public MaterialAutoCompleteTextView(
    @NonNull Context context, @Nullable AttributeSet attributeSet, int defStyleAttr) {
  super(wrap(context, attributeSet, defStyleAttr, 0), attributeSet, defStyleAttr);
  // Ensure we are using the correctly themed context rather than the context that was passed in.
  context = getContext();

  TypedArray attributes =
      ThemeEnforcement.obtainStyledAttributes(
          context,
          attributeSet,
          R.styleable.MaterialAutoCompleteTextView,
          defStyleAttr,
          R.style.Widget_AppCompat_AutoCompleteTextView);

  // Due to a framework bug, setting android:inputType="none" on xml has no effect. Therefore,
  // we check it here in case the autoCompleteTextView should be non-editable.
  if (attributes.hasValue(R.styleable.MaterialAutoCompleteTextView_android_inputType)) {
    int inputType =
        attributes.getInt(
            R.styleable.MaterialAutoCompleteTextView_android_inputType, InputType.TYPE_NULL);
    if (inputType == InputType.TYPE_NULL) {
      setKeyListener(null);
    }
  }

  accessibilityManager =
      (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);

  modalListPopup = new ListPopupWindow(context);
  modalListPopup.setModal(true);
  modalListPopup.setAnchorView(this);
  modalListPopup.setInputMethodMode(ListPopupWindow.INPUT_METHOD_NOT_NEEDED);
  modalListPopup.setAdapter(getAdapter());
  modalListPopup.setOnItemClickListener(
      new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View selectedView, int position, long id) {
          Object selectedItem =
              position < 0 ? modalListPopup.getSelectedItem() : getAdapter().getItem(position);

          updateText(selectedItem);

          OnItemClickListener userOnitemClickListener = getOnItemClickListener();
          if (userOnitemClickListener != null) {
            if (selectedView == null || position < 0) {
              selectedView = modalListPopup.getSelectedView();
              position = modalListPopup.getSelectedItemPosition();
              id = modalListPopup.getSelectedItemId();
            }
            userOnitemClickListener.onItemClick(
                modalListPopup.getListView(), selectedView, position, id);
          }

          modalListPopup.dismiss();
        }
      });

  attributes.recycle();
}
 
Example 12
Source File: SubtitleCollapsingToolbarLayout.java    From collapsingtoolbarlayout-subtitle with Apache License 2.0 4 votes vote down vote up
public SubtitleCollapsingToolbarLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    collapsingTextHelper = new SubtitleCollapsingTextHelper(this);
    collapsingTextHelper.setTextSizeInterpolator(AnimationUtils.DECELERATE_INTERPOLATOR);

    TypedArray a = ThemeEnforcement.obtainStyledAttributes(
        context,
        attrs,
        R.styleable.SubtitleCollapsingToolbarLayout,
        defStyleAttr,
        R.style.Widget_Design_SubtitleCollapsingToolbar);

    collapsingTextHelper.setExpandedTextGravity(a.getInt(
        R.styleable.SubtitleCollapsingToolbarLayout_expandedTitleGravity,
        GravityCompat.START | Gravity.BOTTOM));
    collapsingTextHelper.setCollapsedTextGravity(a.getInt(
        R.styleable.SubtitleCollapsingToolbarLayout_collapsedTitleGravity,
        GravityCompat.START | Gravity.CENTER_VERTICAL));

    expandedMarginStart = expandedMarginTop = expandedMarginEnd = expandedMarginBottom =
        a.getDimensionPixelSize(R.styleable.SubtitleCollapsingToolbarLayout_expandedTitleMargin, 0);

    if (a.hasValue(R.styleable.SubtitleCollapsingToolbarLayout_expandedTitleMarginStart)) {
        expandedMarginStart =
            a.getDimensionPixelSize(R.styleable.SubtitleCollapsingToolbarLayout_expandedTitleMarginStart, 0);
    }
    if (a.hasValue(R.styleable.SubtitleCollapsingToolbarLayout_expandedTitleMarginEnd)) {
        expandedMarginEnd =
            a.getDimensionPixelSize(R.styleable.SubtitleCollapsingToolbarLayout_expandedTitleMarginEnd, 0);
    }
    if (a.hasValue(R.styleable.SubtitleCollapsingToolbarLayout_expandedTitleMarginTop)) {
        expandedMarginTop =
            a.getDimensionPixelSize(R.styleable.SubtitleCollapsingToolbarLayout_expandedTitleMarginTop, 0);
    }
    if (a.hasValue(R.styleable.SubtitleCollapsingToolbarLayout_expandedTitleMarginBottom)) {
        expandedMarginBottom =
            a.getDimensionPixelSize(R.styleable.SubtitleCollapsingToolbarLayout_expandedTitleMarginBottom, 0);
    }

    collapsingTitleEnabled = a.getBoolean(R.styleable.SubtitleCollapsingToolbarLayout_titleEnabled, true);
    setTitle(a.getText(R.styleable.SubtitleCollapsingToolbarLayout_title));
    setSubtitle(a.getText(R.styleable.SubtitleCollapsingToolbarLayout_subtitle));

    // First load the default text appearances
    collapsingTextHelper.setExpandedTitleTextAppearance(
        R.style.TextAppearance_Design_SubtitleCollapsingToolbar_ExpandedTitle);
    collapsingTextHelper.setCollapsedTitleTextAppearance(
        androidx.appcompat.R.style.TextAppearance_AppCompat_Widget_ActionBar_Title);
    collapsingTextHelper.setExpandedSubtitleTextAppearance(
        R.style.TextAppearance_Design_SubtitleCollapsingToolbar_ExpandedSubtitle);
    collapsingTextHelper.setCollapsedSubtitleTextAppearance(
        androidx.appcompat.R.style.TextAppearance_AppCompat_Widget_ActionBar_Subtitle);

    // Now overlay any custom text appearances
    if (a.hasValue(R.styleable.SubtitleCollapsingToolbarLayout_expandedTitleTextAppearance)) {
        collapsingTextHelper.setExpandedTitleTextAppearance(
            a.getResourceId(R.styleable.SubtitleCollapsingToolbarLayout_expandedTitleTextAppearance, 0));
    }
    if (a.hasValue(R.styleable.SubtitleCollapsingToolbarLayout_collapsedTitleTextAppearance)) {
        collapsingTextHelper.setCollapsedTitleTextAppearance(
            a.getResourceId(R.styleable.SubtitleCollapsingToolbarLayout_collapsedTitleTextAppearance, 0));
    }
    if (a.hasValue(R.styleable.SubtitleCollapsingToolbarLayout_expandedSubtitleTextAppearance)) {
        collapsingTextHelper.setExpandedSubtitleTextAppearance(
            a.getResourceId(R.styleable.SubtitleCollapsingToolbarLayout_expandedSubtitleTextAppearance, 0));
    }
    if (a.hasValue(R.styleable.SubtitleCollapsingToolbarLayout_collapsedSubtitleTextAppearance)) {
        collapsingTextHelper.setCollapsedSubtitleTextAppearance(
            a.getResourceId(R.styleable.SubtitleCollapsingToolbarLayout_collapsedSubtitleTextAppearance, 0));
    }

    scrimVisibleHeightTrigger = a
        .getDimensionPixelSize(R.styleable.SubtitleCollapsingToolbarLayout_scrimVisibleHeightTrigger, -1);

    scrimAnimationDuration = a.getInt(
        R.styleable.SubtitleCollapsingToolbarLayout_scrimAnimationDuration,
        DEFAULT_SCRIM_ANIMATION_DURATION);

    setContentScrim(a.getDrawable(R.styleable.SubtitleCollapsingToolbarLayout_contentScrim));
    setStatusBarScrim(a.getDrawable(R.styleable.SubtitleCollapsingToolbarLayout_statusBarScrim));

    toolbarId = a.getResourceId(R.styleable.SubtitleCollapsingToolbarLayout_toolbarId, -1);

    a.recycle();

    setWillNotDraw(false);

    ViewCompat.setOnApplyWindowInsetsListener(this, new androidx.core.view.OnApplyWindowInsetsListener() {
            @Override
            public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                return onWindowInsetChanged(insets);
            }
        }
    );
}
 
Example 13
Source File: BottomAppBar.java    From material-components-android with Apache License 2.0 4 votes vote down vote up
public BottomAppBar(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  super(wrap(context, attrs, defStyleAttr, DEF_STYLE_RES), attrs, defStyleAttr);
  // Ensure we are using the correctly themed context rather than the context that was passed in.
  context = getContext();

  TypedArray a =
      ThemeEnforcement.obtainStyledAttributes(
          context, attrs, R.styleable.BottomAppBar, defStyleAttr, DEF_STYLE_RES);

  ColorStateList backgroundTint =
      MaterialResources.getColorStateList(context, a, R.styleable.BottomAppBar_backgroundTint);

  int elevation = a.getDimensionPixelSize(R.styleable.BottomAppBar_elevation, 0);
  float fabCradleMargin = a.getDimensionPixelOffset(R.styleable.BottomAppBar_fabCradleMargin, 0);
  float fabCornerRadius =
      a.getDimensionPixelOffset(R.styleable.BottomAppBar_fabCradleRoundedCornerRadius, 0);
  float fabVerticalOffset =
      a.getDimensionPixelOffset(R.styleable.BottomAppBar_fabCradleVerticalOffset, 0);
  fabAlignmentMode =
      a.getInt(R.styleable.BottomAppBar_fabAlignmentMode, FAB_ALIGNMENT_MODE_CENTER);
  fabAnimationMode =
      a.getInt(R.styleable.BottomAppBar_fabAnimationMode, FAB_ANIMATION_MODE_SCALE);
  hideOnScroll = a.getBoolean(R.styleable.BottomAppBar_hideOnScroll, false);
  // Reading out if we are handling bottom padding, so we can apply it to the FAB.
  paddingBottomSystemWindowInsets =
      a.getBoolean(R.styleable.BottomAppBar_paddingBottomSystemWindowInsets, false);
  paddingLeftSystemWindowInsets =
      a.getBoolean(R.styleable.BottomAppBar_paddingLeftSystemWindowInsets, false);
  paddingRightSystemWindowInsets =
      a.getBoolean(R.styleable.BottomAppBar_paddingRightSystemWindowInsets, false);

  a.recycle();

  fabOffsetEndMode =
      getResources().getDimensionPixelOffset(R.dimen.mtrl_bottomappbar_fabOffsetEndMode);

  EdgeTreatment topEdgeTreatment =
      new BottomAppBarTopEdgeTreatment(fabCradleMargin, fabCornerRadius, fabVerticalOffset);
  ShapeAppearanceModel shapeAppearanceModel =
      ShapeAppearanceModel.builder().setTopEdge(topEdgeTreatment).build();
  materialShapeDrawable.setShapeAppearanceModel(shapeAppearanceModel);
  materialShapeDrawable.setShadowCompatibilityMode(SHADOW_COMPAT_MODE_ALWAYS);
  materialShapeDrawable.setPaintStyle(Style.FILL);
  materialShapeDrawable.initializeElevationOverlay(context);
  setElevation(elevation);
  DrawableCompat.setTintList(materialShapeDrawable, backgroundTint);
  ViewCompat.setBackground(this, materialShapeDrawable);

  ViewUtils.doOnApplyWindowInsets(
      this,
      attrs,
      defStyleAttr,
      DEF_STYLE_RES,
      new ViewUtils.OnApplyWindowInsetsListener() {
        @NonNull
        @Override
        public WindowInsetsCompat onApplyWindowInsets(
            View view,
            @NonNull WindowInsetsCompat insets,
            @NonNull RelativePadding initialPadding) {
          // Just read the insets here. doOnApplyWindowInsets will apply the padding under the
          // hood.
          boolean leftInsetsChanged = false;
          boolean rightInsetsChanged = false;
          if (paddingBottomSystemWindowInsets) {
            bottomInset = insets.getSystemWindowInsetBottom();
          }
          if (paddingLeftSystemWindowInsets) {
            leftInsetsChanged = leftInset != insets.getSystemWindowInsetLeft();
            leftInset = insets.getSystemWindowInsetLeft();
          }
          if (paddingRightSystemWindowInsets) {
            rightInsetsChanged = rightInset != insets.getSystemWindowInsetRight();
            rightInset = insets.getSystemWindowInsetRight();
          }

          // We may need to change the position of the cutout or the action menu if the side
          // insets have changed.
          if (leftInsetsChanged || rightInsetsChanged) {
            cancelAnimations();

            setCutoutState();
            setActionMenuViewPosition();
          }

          return insets;
        }
      });
}
 
Example 14
Source File: AppBarLayout.java    From material-components-android with Apache License 2.0 4 votes vote down vote up
public AppBarLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  super(wrap(context, attrs, defStyleAttr, DEF_STYLE_RES), attrs, defStyleAttr);
  // Ensure we are using the correctly themed context rather than the context that was passed in.
  context = getContext();
  setOrientation(VERTICAL);

  if (Build.VERSION.SDK_INT >= 21) {
    // Use the bounds view outline provider so that we cast a shadow, even without a
    // background
    ViewUtilsLollipop.setBoundsViewOutlineProvider(this);

    // If we're running on API 21+, we should reset any state list animator from our
    // default style
    ViewUtilsLollipop.setStateListAnimatorFromAttrs(
        this, attrs, defStyleAttr, DEF_STYLE_RES);
  }

  final TypedArray a =
      ThemeEnforcement.obtainStyledAttributes(
          context,
          attrs,
          R.styleable.AppBarLayout,
          defStyleAttr,
          DEF_STYLE_RES);

  ViewCompat.setBackground(this, a.getDrawable(R.styleable.AppBarLayout_android_background));

  if (getBackground() instanceof ColorDrawable) {
    ColorDrawable background = (ColorDrawable) getBackground();
    MaterialShapeDrawable materialShapeDrawable = new MaterialShapeDrawable();
    materialShapeDrawable.setFillColor(ColorStateList.valueOf(background.getColor()));
    materialShapeDrawable.initializeElevationOverlay(context);
    ViewCompat.setBackground(this, materialShapeDrawable);
  }

  if (a.hasValue(R.styleable.AppBarLayout_expanded)) {
    setExpanded(
        a.getBoolean(R.styleable.AppBarLayout_expanded, false),
        false, /* animate */
        false /* force */);
  }

  if (Build.VERSION.SDK_INT >= 21 && a.hasValue(R.styleable.AppBarLayout_elevation)) {
    ViewUtilsLollipop.setDefaultAppBarLayoutStateListAnimator(
        this, a.getDimensionPixelSize(R.styleable.AppBarLayout_elevation, 0));
  }

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    // In O+, we have these values set in the style. Since there is no defStyleAttr for
    // AppBarLayout at the AppCompat level, check for these attributes here.
    if (a.hasValue(R.styleable.AppBarLayout_android_keyboardNavigationCluster)) {
      this.setKeyboardNavigationCluster(
          a.getBoolean(R.styleable.AppBarLayout_android_keyboardNavigationCluster, false));
    }
    if (a.hasValue(R.styleable.AppBarLayout_android_touchscreenBlocksFocus)) {
      this.setTouchscreenBlocksFocus(
          a.getBoolean(R.styleable.AppBarLayout_android_touchscreenBlocksFocus, false));
    }
  }

  liftOnScroll = a.getBoolean(R.styleable.AppBarLayout_liftOnScroll, false);
  liftOnScrollTargetViewId =
      a.getResourceId(R.styleable.AppBarLayout_liftOnScrollTargetViewId, View.NO_ID);

  setStatusBarForeground(a.getDrawable(R.styleable.AppBarLayout_statusBarForeground));
  a.recycle();

  ViewCompat.setOnApplyWindowInsetsListener(
      this,
      new androidx.core.view.OnApplyWindowInsetsListener() {
        @Override
        public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
          return onWindowInsetChanged(insets);
        }
      });
}
 
Example 15
Source File: FloatingActionButton.java    From material-components-android with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("nullness")
public FloatingActionButton(
    @NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  super(wrap(context, attrs, defStyleAttr, DEF_STYLE_RES), attrs, defStyleAttr);
  // Ensure we are using the correctly themed context rather than the context that was passed in.
  context = getContext();

  TypedArray a =
      ThemeEnforcement.obtainStyledAttributes(
          context, attrs, R.styleable.FloatingActionButton, defStyleAttr, DEF_STYLE_RES);

  backgroundTint =
      MaterialResources.getColorStateList(
          context, a, R.styleable.FloatingActionButton_backgroundTint);
  backgroundTintMode =
      ViewUtils.parseTintMode(
          a.getInt(R.styleable.FloatingActionButton_backgroundTintMode, -1), null);
  rippleColor =
      MaterialResources.getColorStateList(
          context, a, R.styleable.FloatingActionButton_rippleColor);
  size = a.getInt(R.styleable.FloatingActionButton_fabSize, SIZE_AUTO);
  customSize =
      a.getDimensionPixelSize(R.styleable.FloatingActionButton_fabCustomSize, NO_CUSTOM_SIZE);
  borderWidth = a.getDimensionPixelSize(R.styleable.FloatingActionButton_borderWidth, 0);
  final float elevation = a.getDimension(R.styleable.FloatingActionButton_elevation, 0f);
  final float hoveredFocusedTranslationZ =
      a.getDimension(R.styleable.FloatingActionButton_hoveredFocusedTranslationZ, 0f);
  final float pressedTranslationZ =
      a.getDimension(R.styleable.FloatingActionButton_pressedTranslationZ, 0f);
  compatPadding = a.getBoolean(R.styleable.FloatingActionButton_useCompatPadding, false);
  int minTouchTargetSize =
      getResources().getDimensionPixelSize(R.dimen.mtrl_fab_min_touch_target);
  maxImageSize = a.getDimensionPixelSize(R.styleable.FloatingActionButton_maxImageSize, 0);

  MotionSpec showMotionSpec =
      MotionSpec.createFromAttribute(context, a, R.styleable.FloatingActionButton_showMotionSpec);
  MotionSpec hideMotionSpec =
      MotionSpec.createFromAttribute(context, a, R.styleable.FloatingActionButton_hideMotionSpec);
  ShapeAppearanceModel shapeAppearance =
      ShapeAppearanceModel.builder(
              context, attrs, defStyleAttr, DEF_STYLE_RES, ShapeAppearanceModel.PILL)
          .build();

  boolean ensureMinTouchTargetSize =
      a.getBoolean(R.styleable.FloatingActionButton_ensureMinTouchTargetSize, false);

  setEnabled(a.getBoolean(R.styleable.FloatingActionButton_android_enabled, true));

  a.recycle();

  imageHelper = new AppCompatImageHelper(this);
  imageHelper.loadFromAttributes(attrs, defStyleAttr);

  expandableWidgetHelper = new ExpandableWidgetHelper(this);

  getImpl().setShapeAppearance(shapeAppearance);
  getImpl()
      .initializeBackgroundDrawable(backgroundTint, backgroundTintMode, rippleColor, borderWidth);
  getImpl().setMinTouchTargetSize(minTouchTargetSize);
  getImpl().setElevation(elevation);
  getImpl().setHoveredFocusedTranslationZ(hoveredFocusedTranslationZ);
  getImpl().setPressedTranslationZ(pressedTranslationZ);
  getImpl().setMaxImageSize(maxImageSize);
  getImpl().setShowMotionSpec(showMotionSpec);
  getImpl().setHideMotionSpec(hideMotionSpec);
  getImpl().setEnsureMinTouchTargetSize(ensureMinTouchTargetSize);

  setScaleType(ScaleType.MATRIX);
}
 
Example 16
Source File: ExtendedFloatingActionButton.java    From material-components-android with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("nullness")
public ExtendedFloatingActionButton(
    @NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  super(wrap(context, attrs, defStyleAttr, DEF_STYLE_RES), attrs, defStyleAttr);
  // Ensure we are using the correctly themed context rather than the context that was passed in.
  context = getContext();
  behavior = new ExtendedFloatingActionButtonBehavior<>(context, attrs);
  TypedArray a =
      ThemeEnforcement.obtainStyledAttributes(
          context, attrs, R.styleable.ExtendedFloatingActionButton, defStyleAttr, DEF_STYLE_RES);

  MotionSpec showMotionSpec =
      MotionSpec.createFromAttribute(
          context, a, R.styleable.ExtendedFloatingActionButton_showMotionSpec);
  MotionSpec hideMotionSpec =
      MotionSpec.createFromAttribute(
          context, a, R.styleable.ExtendedFloatingActionButton_hideMotionSpec);
  MotionSpec extendMotionSpec =
      MotionSpec.createFromAttribute(
          context, a, R.styleable.ExtendedFloatingActionButton_extendMotionSpec);
  MotionSpec shrinkMotionSpec =
      MotionSpec.createFromAttribute(
          context, a, R.styleable.ExtendedFloatingActionButton_shrinkMotionSpec);

  AnimatorTracker changeSizeTracker = new AnimatorTracker();
  extendStrategy = new ChangeSizeStrategy(
      changeSizeTracker,
      new Size() {
        @Override
        public int getWidth() {
          return getMeasuredWidth();
        }

        @Override
        public int getHeight() {
          return getMeasuredHeight();
        }

        @Override
        public LayoutParams getLayoutParams() {
          return new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
        }
      },
      /* extending= */ true);

  shrinkStrategy = new ChangeSizeStrategy(
      changeSizeTracker,
      new Size() {
        @Override
        public int getWidth() {
          return getCollapsedSize();
        }

        @Override
        public int getHeight() {
          return getCollapsedSize();
        }

        @Override
        public LayoutParams getLayoutParams() {
          return new LayoutParams(getWidth(), getHeight());
        }
      },
      /* extending= */ false);

  showStrategy.setMotionSpec(showMotionSpec);
  hideStrategy.setMotionSpec(hideMotionSpec);
  extendStrategy.setMotionSpec(extendMotionSpec);
  shrinkStrategy.setMotionSpec(shrinkMotionSpec);
  a.recycle();

  ShapeAppearanceModel shapeAppearanceModel =
      ShapeAppearanceModel.builder(
          context, attrs, defStyleAttr, DEF_STYLE_RES, ShapeAppearanceModel.PILL
      ).build();
  setShapeAppearanceModel(shapeAppearanceModel);
}
 
Example 17
Source File: BaseSlider.java    From material-components-android with Apache License 2.0 4 votes vote down vote up
private void processAttributes(Context context, AttributeSet attrs, int defStyleAttr) {
  TypedArray a =
      ThemeEnforcement.obtainStyledAttributes(
          context, attrs, R.styleable.Slider, defStyleAttr, DEF_STYLE_RES);
  valueFrom = a.getFloat(R.styleable.Slider_android_valueFrom, 0.0f);
  valueTo = a.getFloat(R.styleable.Slider_android_valueTo, 1.0f);
  setValues(valueFrom);
  stepSize = a.getFloat(R.styleable.Slider_android_stepSize, 0.0f);

  boolean hasTrackColor = a.hasValue(R.styleable.Slider_trackColor);

  int trackColorInactiveRes =
      hasTrackColor ? R.styleable.Slider_trackColor : R.styleable.Slider_trackColorInactive;
  int trackColorActiveRes =
      hasTrackColor ? R.styleable.Slider_trackColor : R.styleable.Slider_trackColorActive;

  ColorStateList trackColorInactive =
      MaterialResources.getColorStateList(context, a, trackColorInactiveRes);
  setTrackInactiveTintList(
      trackColorInactive != null
          ? trackColorInactive
          : AppCompatResources.getColorStateList(
              context, R.color.material_slider_inactive_track_color));
  ColorStateList trackColorActive =
      MaterialResources.getColorStateList(context, a, trackColorActiveRes);
  setTrackActiveTintList(
      trackColorActive != null
          ? trackColorActive
          : AppCompatResources.getColorStateList(
              context, R.color.material_slider_active_track_color));
  ColorStateList thumbColor =
      MaterialResources.getColorStateList(context, a, R.styleable.Slider_thumbColor);
  thumbDrawable.setFillColor(thumbColor);
  ColorStateList haloColor =
      MaterialResources.getColorStateList(context, a, R.styleable.Slider_haloColor);
  setHaloTintList(
      haloColor != null
          ? haloColor
          : AppCompatResources.getColorStateList(context, R.color.material_slider_halo_color));

  boolean hasTickColor = a.hasValue(R.styleable.Slider_tickColor);
  int tickColorInactiveRes =
      hasTickColor ? R.styleable.Slider_tickColor : R.styleable.Slider_tickColorInactive;
  int tickColorActiveRes =
      hasTickColor ? R.styleable.Slider_tickColor : R.styleable.Slider_tickColorActive;
  ColorStateList tickColorInactive =
      MaterialResources.getColorStateList(context, a, tickColorInactiveRes);
  setTickInactiveTintList(
      tickColorInactive != null
          ? tickColorInactive
          : AppCompatResources.getColorStateList(
              context, R.color.material_slider_inactive_tick_marks_color));
  ColorStateList tickColorActive =
      MaterialResources.getColorStateList(context, a, tickColorActiveRes);
  setTickActiveTintList(
      tickColorActive != null
          ? tickColorActive
          : AppCompatResources.getColorStateList(
              context, R.color.material_slider_active_tick_marks_color));

  setThumbRadius(a.getDimensionPixelSize(R.styleable.Slider_thumbRadius, 0));
  setHaloRadius(a.getDimensionPixelSize(R.styleable.Slider_haloRadius, 0));

  setThumbElevation(a.getDimension(R.styleable.Slider_thumbElevation, 0));

  setTrackHeight(a.getDimensionPixelSize(R.styleable.Slider_trackHeight, 0));

  labelBehavior = a.getInt(R.styleable.Slider_labelBehavior, LABEL_FLOATING);
  a.recycle();
}
 
Example 18
Source File: BaseSlider.java    From material-components-android with Apache License 2.0 4 votes vote down vote up
public BaseSlider(
    @NonNull Context context, @Nullable final AttributeSet attrs, final int defStyleAttr) {
  super(wrap(context, attrs, defStyleAttr, DEF_STYLE_RES), attrs, defStyleAttr);
  // Ensure we are using the correctly themed context rather than the context that was passed in.
  context = getContext();

  inactiveTrackPaint = new Paint();
  inactiveTrackPaint.setStyle(Style.STROKE);
  inactiveTrackPaint.setStrokeCap(Cap.ROUND);

  activeTrackPaint = new Paint();
  activeTrackPaint.setStyle(Style.STROKE);
  activeTrackPaint.setStrokeCap(Cap.ROUND);

  thumbPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
  thumbPaint.setStyle(Style.FILL);
  thumbPaint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));

  haloPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
  haloPaint.setStyle(Style.FILL);

  inactiveTicksPaint = new Paint();
  inactiveTicksPaint.setStyle(Style.STROKE);
  inactiveTicksPaint.setStrokeCap(Cap.ROUND);

  activeTicksPaint = new Paint();
  activeTicksPaint.setStyle(Style.STROKE);
  activeTicksPaint.setStrokeCap(Cap.ROUND);

  loadResources(context.getResources());

  // Because there's currently no way to copy the TooltipDrawable we use this to make more if more
  // thumbs are added.
  labelMaker =
      new TooltipDrawableFactory() {
        @Override
        public TooltipDrawable createTooltipDrawable() {
          final TypedArray a =
              ThemeEnforcement.obtainStyledAttributes(
                  getContext(), attrs, R.styleable.Slider, defStyleAttr, DEF_STYLE_RES);
          TooltipDrawable d = parseLabelDrawable(getContext(), a);
          a.recycle();
          return d;
        }
      };

  processAttributes(context, attrs, defStyleAttr);

  setFocusable(true);
  setClickable(true);

  // Set up the thumb drawable to always show the compat shadow.
  thumbDrawable.setShadowCompatibilityMode(MaterialShapeDrawable.SHADOW_COMPAT_MODE_ALWAYS);

  scaledTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();

  accessibilityHelper = new AccessibilityHelper(this);
  ViewCompat.setAccessibilityDelegate(this, accessibilityHelper);

  accessibilityManager =
      (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
}
 
Example 19
Source File: TooltipDrawable.java    From material-components-android with Apache License 2.0 4 votes vote down vote up
private void loadFromAttributes(
    @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
  TypedArray a =
      ThemeEnforcement.obtainStyledAttributes(
          context, attrs, R.styleable.Tooltip, defStyleAttr, defStyleRes);

  arrowSize = context.getResources().getDimensionPixelSize(R.dimen.mtrl_tooltip_arrowSize);
  setShapeAppearanceModel(
      getShapeAppearanceModel().toBuilder().setBottomEdge(createMarkerEdge()).build());

  setText(a.getText(R.styleable.Tooltip_android_text));
  setTextAppearance(
      MaterialResources.getTextAppearance(
          context, a, R.styleable.Tooltip_android_textAppearance));

  int onBackground =
      MaterialColors.getColor(
          context, R.attr.colorOnBackground, TooltipDrawable.class.getCanonicalName());
  int background =
      MaterialColors.getColor(
          context, android.R.attr.colorBackground, TooltipDrawable.class.getCanonicalName());

  int backgroundTintDefault =
      MaterialColors.layer(
          ColorUtils.setAlphaComponent(background, (int) (0.9f * 255)),
          ColorUtils.setAlphaComponent(onBackground, (int) (0.6f * 255)));
  setFillColor(
      ColorStateList.valueOf(
          a.getColor(R.styleable.Tooltip_backgroundTint, backgroundTintDefault)));

  setStrokeColor(
      ColorStateList.valueOf(
          MaterialColors.getColor(
              context, R.attr.colorSurface, TooltipDrawable.class.getCanonicalName())));

  padding = a.getDimensionPixelSize(R.styleable.Tooltip_android_padding, 0);
  minWidth = a.getDimensionPixelSize(R.styleable.Tooltip_android_minWidth, 0);
  minHeight = a.getDimensionPixelSize(R.styleable.Tooltip_android_minHeight, 0);
  layoutMargin = a.getDimensionPixelSize(R.styleable.Tooltip_android_layout_margin, 0);

  a.recycle();
}
 
Example 20
Source File: MaterialDialogs.java    From material-components-android with Apache License 2.0 4 votes vote down vote up
@NonNull
public static Rect getDialogBackgroundInsets(
    @NonNull Context context, @AttrRes int defaultStyleAttribute, int defaultStyleResource) {
  TypedArray attributes =
      ThemeEnforcement.obtainStyledAttributes(
          context,
          null,
          R.styleable.MaterialAlertDialog,
          defaultStyleAttribute,
          defaultStyleResource);

  int backgroundInsetStart =
      attributes.getDimensionPixelSize(
          R.styleable.MaterialAlertDialog_backgroundInsetStart,
          context
              .getResources()
              .getDimensionPixelSize(R.dimen.mtrl_alert_dialog_background_inset_start));
  int backgroundInsetTop =
      attributes.getDimensionPixelSize(
          R.styleable.MaterialAlertDialog_backgroundInsetTop,
          context
              .getResources()
              .getDimensionPixelSize(R.dimen.mtrl_alert_dialog_background_inset_top));

  int backgroundInsetEnd =
      attributes.getDimensionPixelSize(
          R.styleable.MaterialAlertDialog_backgroundInsetEnd,
          context
              .getResources()
              .getDimensionPixelSize(R.dimen.mtrl_alert_dialog_background_inset_end));
  int backgroundInsetBottom =
      attributes.getDimensionPixelSize(
          R.styleable.MaterialAlertDialog_backgroundInsetBottom,
          context
              .getResources()
              .getDimensionPixelSize(R.dimen.mtrl_alert_dialog_background_inset_bottom));

  attributes.recycle();

  int backgroundInsetLeft = backgroundInsetStart;
  int backgroundInsetRight = backgroundInsetEnd;
  if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) {
    int layoutDirection = context.getResources().getConfiguration().getLayoutDirection();
    if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) {
      backgroundInsetLeft = backgroundInsetEnd;
      backgroundInsetRight = backgroundInsetStart;
    }
  }

  return new Rect(
      backgroundInsetLeft, backgroundInsetTop, backgroundInsetRight, backgroundInsetBottom);
}