Java Code Examples for androidx.core.view.ViewCompat#setBackground()

The following examples show how to use androidx.core.view.ViewCompat#setBackground() . 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: ElevationAnimationDemoFragment.java    From material-components-android with Apache License 2.0 6 votes vote down vote up
@Override
public View onCreateDemoView(
    LayoutInflater layoutInflater, @Nullable ViewGroup viewGroup, @Nullable Bundle bundle) {
  View view =
      layoutInflater.inflate(
          R.layout.cat_elevation_animation_fragment, viewGroup, false /* attachToRoot */);

  TextView translationZLabelView = view.findViewById(R.id.translation_z_label);

  float maxTranslationZ = getResources().getDimension(R.dimen.cat_elevation_max_translation_z);
  int maxTranslationZDp = (int) (maxTranslationZ / getResources().getDisplayMetrics().density);
  translationZLabelView.setText(
      getString(R.string.cat_elevation_animation_label, maxTranslationZDp));

  MaterialShapeDrawable materialShapeDrawable =
      MaterialShapeDrawable.createWithElevationOverlay(view.getContext());
  ViewCompat.setBackground(view, materialShapeDrawable);
  setTranslationZ(view, materialShapeDrawable, maxTranslationZ);
  startTranslationZAnimation(view, materialShapeDrawable, maxTranslationZ);

  return view;
}
 
Example 2
Source File: RadialViewGroup.java    From material-components-android with Apache License 2.0 6 votes vote down vote up
public RadialViewGroup(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  super(context, attrs, defStyleAttr);
  LayoutInflater.from(context).inflate(R.layout.material_radial_view_group, this);
  ViewCompat.setBackground(this, createBackground());

  TypedArray a =
      context.obtainStyledAttributes(attrs, R.styleable.RadialViewGroup, defStyleAttr, 0);
  radius = a.getDimensionPixelSize(R.styleable.RadialViewGroup_radius, 0);
  updateLayoutParametersRunnable = new Runnable() {
    @Override
    public void run() {
      updateLayoutParams();
    }
  };
  a.recycle();
}
 
Example 3
Source File: FastScroller.java    From HaoReader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Set the background color of the section bubble.
 *
 * @param color The background color for the section bubble
 */
public void setBubbleColor(@ColorInt int color) {
    bubbleColor = color;

    if (bubbleImage == null) {
        Drawable drawable = ContextCompat.getDrawable(getContext(), bubbleSize.drawableId);

        if (drawable != null) {
            bubbleImage = DrawableCompat.wrap(drawable);
            bubbleImage.mutate();
        }
    }

    DrawableCompat.setTint(bubbleImage, bubbleColor);
    ViewCompat.setBackground(bubbleView, bubbleImage);
}
 
Example 4
Source File: NavigationMenuItemView.java    From material-components-android with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(@NonNull MenuItemImpl itemData, int menuType) {
  this.itemData = itemData;
  if (itemData.getItemId() > 0) {
    setId(itemData.getItemId());
  }

  setVisibility(itemData.isVisible() ? VISIBLE : GONE);

  if (getBackground() == null) {
    ViewCompat.setBackground(this, createDefaultBackground());
  }

  setCheckable(itemData.isCheckable());
  setChecked(itemData.isChecked());
  setEnabled(itemData.isEnabled());
  setTitle(itemData.getTitle());
  setIcon(itemData.getIcon());
  setActionView(itemData.getActionView());
  setContentDescription(itemData.getContentDescription());
  TooltipCompat.setTooltipText(this, itemData.getTooltipText());
  adjustAppearance();
}
 
Example 5
Source File: NumberButton.java    From HaoReader with GNU General Public License v3.0 6 votes vote down vote up
private void init(Context context, AttributeSet attrs) {
    LayoutInflater.from(context).inflate(R.layout.view_number_buttom, this);

    TextView addButton = findViewById(R.id.button_add);
    addButton.setOnClickListener(this);
    TextView subButton = findViewById(R.id.button_sub);
    subButton.setOnClickListener(this);
    tvNumber = findViewById(R.id.tv_number);
    tvNumber.setOnClickListener(this);

    TypedArray a = context.obtainStyledAttributes(attrs,
            R.styleable.NumberButton, 0, 0);
    if(a.hasValue(R.styleable.NumberButton_themeColor)){
        int themeColor = a.getColor(R.styleable.NumberButton_themeColor, context.getResources().getColor(R.color.colorTextDefault));
        addButton.setTextColor(themeColor);
        subButton.setTextColor(themeColor);
        tvNumber.setTextColor(themeColor);
    }
    if(a.hasValue(R.styleable.NumberButton_android_background)){
        ViewCompat.setBackground(this, null);
        ViewCompat.setBackground(getChildAt(0), a.getDrawable(R.styleable.NumberButton_android_background));
    }
    a.recycle();
}
 
Example 6
Source File: CreditsAdapter.java    From candybar with Apache License 2.0 5 votes vote down vote up
ViewHolder(View view) {
    container = view.findViewById(R.id.container);
    title = view.findViewById(R.id.title);
    subtitle = view.findViewById(R.id.subtitle);
    image = view.findViewById(R.id.image);

    int color = ColorHelper.getAttributeColor(mContext, android.R.attr.textColorSecondary);
    ViewCompat.setBackground(image, DrawableHelper.getTintedDrawable(
            mContext, R.drawable.ic_toolbar_circle, ColorHelper.setColorAlpha(color, 0.4f)));
}
 
Example 7
Source File: SwipeMenuView.java    From SwipeRecyclerView with Apache License 2.0 5 votes vote down vote up
public void createMenu(RecyclerView.ViewHolder viewHolder, SwipeMenu swipeMenu, Controller controller,
    int direction, OnItemMenuClickListener itemClickListener) {
    removeAllViews();

    this.mViewHolder = viewHolder;
    this.mItemClickListener = itemClickListener;

    List<SwipeMenuItem> items = swipeMenu.getMenuItems();
    for (int i = 0; i < items.size(); i++) {
        SwipeMenuItem item = items.get(i);

        LayoutParams params = new LayoutParams(item.getWidth(), item.getHeight());
        params.weight = item.getWeight();
        LinearLayout parent = new LinearLayout(getContext());
        parent.setId(i);
        parent.setGravity(Gravity.CENTER);
        parent.setOrientation(VERTICAL);
        parent.setLayoutParams(params);
        ViewCompat.setBackground(parent, item.getBackground());
        parent.setOnClickListener(this);
        addView(parent);

        SwipeMenuBridge menuBridge = new SwipeMenuBridge(controller, direction, i);
        parent.setTag(menuBridge);

        if (item.getImage() != null) {
            ImageView iv = createIcon(item);
            parent.addView(iv);
        }

        if (!TextUtils.isEmpty(item.getText())) {
            TextView tv = createTitle(item);
            parent.addView(tv);
        }
    }
}
 
Example 8
Source File: BaseTransientBottomBar.java    From material-components-android with Apache License 2.0 5 votes vote down vote up
protected SnackbarBaseLayout(@NonNull Context context, AttributeSet attrs) {
  super(wrap(context, attrs, 0, 0), attrs);
  // Ensure we are using the correctly themed context rather than the context that was passed
  // in.
  context = getContext();
  TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SnackbarLayout);
  if (a.hasValue(R.styleable.SnackbarLayout_elevation)) {
    ViewCompat.setElevation(
        this, a.getDimensionPixelSize(R.styleable.SnackbarLayout_elevation, 0));
  }
  animationMode = a.getInt(R.styleable.SnackbarLayout_animationMode, ANIMATION_MODE_SLIDE);
  backgroundOverlayColorAlpha =
      a.getFloat(R.styleable.SnackbarLayout_backgroundOverlayColorAlpha, 1);
  setBackgroundTintList(
      MaterialResources.getColorStateList(
          context, a, R.styleable.SnackbarLayout_backgroundTint));
  setBackgroundTintMode(
      ViewUtils.parseTintMode(
          a.getInt(R.styleable.SnackbarLayout_backgroundTintMode, -1), PorterDuff.Mode.SRC_IN));
  actionTextColorAlpha = a.getFloat(R.styleable.SnackbarLayout_actionTextColorAlpha, 1);
  a.recycle();

  setOnTouchListener(consumeAllTouchListener);
  setFocusable(true);

  if (getBackground() == null) {
    ViewCompat.setBackground(this, createThemedBackground());
  }
}
 
Example 9
Source File: ArticlesAdapter.java    From WanAndroid with Apache License 2.0 5 votes vote down vote up
@Override
protected void convert(BaseViewHolder holder, Article article) {
    if(article == null) return;

    holder.setText(R.id.tv_title, Html.fromHtml(article.getTitle()))
            .setText(R.id.tv_author, "作者:" + article.getAuthor())
            .setText(R.id.tv_classify, "分类:" + article.getChapterName())
            .setText(R.id.tv_publish_time, article.getNiceDate())
            .addOnClickListener(R.id.iv_collection);

    if(article.isCollect()){
        holder.setImageDrawable(
                R.id.iv_collection,
                CommonUtil.getTintDrawable(
                        Objects.requireNonNull(ContextCompat.getDrawable(mContext, R.drawable.ic_home_collection)),
                        ColorStateList.valueOf(ContextCompat.getColor(mContext, R.color.colorCollected))
                )
        );
    } else{
        holder.setImageResource(R.id.iv_collection, R.drawable.ic_home_collection);
    }

    TextView textView = holder.getView(R.id.tv_tags);
    textView.setVisibility(View.VISIBLE);
    if(article.isFresh()){
        Drawable freshDrawable = ContextCompat.getDrawable(mContext, R.drawable.bg_tag_tv1);
        ViewCompat.setBackground(textView, freshDrawable);
        textView.setText("最新");
        textView.setTextColor(ContextCompat.getColor(mContext, R.color.colorTag1));
    }else if(!CommonUtil.isEmptyList(article.getTags())){
        Drawable tagDrawable = ContextCompat.getDrawable(mContext, R.drawable.bg_tag_tv2);
        ViewCompat.setBackground(textView, tagDrawable);
        textView.setText(article.getTags().get(0).getName());
        textView.setTextColor(ContextCompat.getColor(mContext, R.color.colorTag2));
    }else {
        textView.setVisibility(View.INVISIBLE);
    }
}
 
Example 10
Source File: DynamicInputUtils.java    From dynamic-support with Apache License 2.0 5 votes vote down vote up
/**
 * Tint the {@link EditText} by changing its cursor, hint, etc. colors according to the
 * supplied color.
 *
 * @param editText The edit text to be colorized.
 * @param background The background color to be used.
 * @param color The color to be used.
 */
public static void setColor(@NonNull EditText editText,
        @ColorInt int background, @ColorInt int color) {
    if (editText.getBackground() != null) {
        ViewCompat.setBackground(editText, DynamicDrawableUtils.colorizeDrawable(
                editText.getBackground(), background));
    }

    setCursorColor(editText, color);
}
 
Example 11
Source File: Chip.java    From material-components-android with Apache License 2.0 5 votes vote down vote up
private void updateBackgroundDrawable() {
  if (RippleUtils.USE_FRAMEWORK_RIPPLE) {
    updateFrameworkRippleBackground();
  } else {
    chipDrawable.setUseCompatRipple(true);
    ViewCompat.setBackground(this, getBackgroundDrawable());
    updatePaddingInternal();
    ensureChipDrawableHasCallback();
  }
}
 
Example 12
Source File: Chip.java    From material-components-android with Apache License 2.0 5 votes vote down vote up
private void updateFrameworkRippleBackground() {
  //noinspection NewApi
  ripple =
      new RippleDrawable(
          RippleUtils.sanitizeRippleDrawableColor(chipDrawable.getRippleColor()),
          getBackgroundDrawable(),
          null);
  chipDrawable.setUseCompatRipple(false);
  //noinspection NewApi
  ViewCompat.setBackground(this, ripple);
  updatePaddingInternal();
}
 
Example 13
Source File: StickyHeaderHelper.java    From FlexibleAdapter with Apache License 2.0 5 votes vote down vote up
private void configureLayoutElevation() {
    // 1. Take elevation from header item layout (most important)
    mElevation = ViewCompat.getElevation(mStickyHeaderViewHolder.getContentView());
    if (mElevation == 0f) {
        // 2. Take elevation settings
        mElevation = mRecyclerView.getContext().getResources().getDisplayMetrics().density
                * mAdapter.getStickyHeaderElevation();
    }
    if (mElevation > 0) {
        // Needed to elevate the view
        ViewCompat.setBackground(mStickyHolderLayout, mStickyHeaderViewHolder.getContentView().getBackground());
    }
}
 
Example 14
Source File: ShadowDrawable.java    From monero-wallet-android-app with MIT License 5 votes vote down vote up
public static void setShadowDrawable(View view, int shape, int bgColor, int shapeRadius, int shadowColor, int shadowRadius, int offsetX, int offsetY) {
    ShadowDrawable drawable = new ShadowDrawable.Builder()
            .setShape(shape)
            .setBgColor(bgColor)
            .setShapeRadius(shapeRadius)
            .setShadowColor(shadowColor)
            .setShadowRadius(shadowRadius)
            .setOffsetX(offsetX)
            .setOffsetY(offsetY)
            .builder();
    view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    ViewCompat.setBackground(view, drawable);
}
 
Example 15
Source File: MaterialToolbar.java    From material-components-android with Apache License 2.0 5 votes vote down vote up
private void initBackground(Context context) {
  Drawable background = getBackground();
  if (background != null && !(background instanceof ColorDrawable)) {
    return;
  }
  MaterialShapeDrawable materialShapeDrawable = new MaterialShapeDrawable();
  int backgroundColor =
      background != null ? ((ColorDrawable) background).getColor() : Color.TRANSPARENT;
  materialShapeDrawable.setFillColor(ColorStateList.valueOf(backgroundColor));
  materialShapeDrawable.initializeElevationOverlay(context);
  materialShapeDrawable.setElevation(ViewCompat.getElevation(this));
  ViewCompat.setBackground(this, materialShapeDrawable);
}
 
Example 16
Source File: BoardFragment.java    From DragListView with Apache License 2.0 5 votes vote down vote up
@Override
public void onBindDragView(View clickedView, View dragView) {
    LinearLayout clickedLayout = (LinearLayout) clickedView;
    View clickedHeader = clickedLayout.getChildAt(0);
    RecyclerView clickedRecyclerView = (RecyclerView) clickedLayout.getChildAt(1);

    View dragHeader = dragView.findViewById(R.id.drag_header);
    ScrollView dragScrollView = dragView.findViewById(R.id.drag_scroll_view);
    LinearLayout dragLayout = dragView.findViewById(R.id.drag_list);

    Drawable clickedColumnBackground = clickedLayout.getBackground();
    if (clickedColumnBackground != null) {
        ViewCompat.setBackground(dragView, clickedColumnBackground);
    }

    Drawable clickedRecyclerBackground = clickedRecyclerView.getBackground();
    if (clickedRecyclerBackground != null) {
        ViewCompat.setBackground(dragLayout, clickedRecyclerBackground);
    }

    dragLayout.removeAllViews();

    ((TextView) dragHeader.findViewById(R.id.text)).setText(((TextView) clickedHeader.findViewById(R.id.text)).getText());
    ((TextView) dragHeader.findViewById(R.id.item_count)).setText(((TextView) clickedHeader.findViewById(R.id.item_count)).getText());
    for (int i = 0; i < clickedRecyclerView.getChildCount(); i++) {
        View view = View.inflate(dragView.getContext(), R.layout.column_item, null);
        ((TextView) view.findViewById(R.id.text)).setText(((TextView) clickedRecyclerView.getChildAt(i).findViewById(R.id.text)).getText());
        dragLayout.addView(view);

        if (i == 0) {
            dragScrollView.setScrollY(-clickedRecyclerView.getChildAt(i).getTop());
        }
    }

    dragView.setPivotY(0);
    dragView.setPivotX(clickedView.getMeasuredWidth() / 2);
}
 
Example 17
Source File: BottomSheetBehavior.java    From bottomsheetrecycler with Apache License 2.0 4 votes vote down vote up
@Override
public boolean onLayoutChild(CoordinatorLayout parent, V child, int layoutDirection) {
    if (ViewCompat.getFitsSystemWindows(parent) && !ViewCompat.getFitsSystemWindows(child)) {
        child.setFitsSystemWindows(true);
    }
    // Only set MaterialShapeDrawable as background if shapeTheming is enabled, otherwise will
    // default to android:background declared in styles or layout.
    if (shapeThemingEnabled && materialShapeDrawable != null) {
        ViewCompat.setBackground(child, materialShapeDrawable);
    }
    // Set elevation on MaterialShapeDrawable
    if (materialShapeDrawable != null) {
        // Use elevation attr if set on bottomsheet; otherwise, use elevation of child view.
        materialShapeDrawable.setElevation(
                elevation == -1 ? ViewCompat.getElevation(child) : elevation);
    }

    if (viewRef == null) {
        // First layout with this behavior.
        peekHeightMin =
                parent.getResources().getDimensionPixelSize(R.dimen.design_bottom_sheet_peek_height_min);
        viewRef = new WeakReference<>(child);
    }
    if (viewDragHelper == null) {
        viewDragHelper = ViewDragHelper.create(parent, dragCallback);
    }

    int savedTop = child.getTop();
    // First let the parent lay it out
    parent.onLayoutChild(child, layoutDirection);
    // Offset the bottom sheet
    parentWidth = parent.getWidth();
    parentHeight = parent.getHeight();
    fitToContentsOffset = Math.max(0, parentHeight - child.getHeight());
    calculateHalfExpandedOffset();
    calculateCollapsedOffset();

    if (state == STATE_EXPANDED) {
        ViewCompat.offsetTopAndBottom(child, getExpandedOffset());
    } else if (state == STATE_HALF_EXPANDED) {
        ViewCompat.offsetTopAndBottom(child, halfExpandedOffset);
    } else if (hideable && state == STATE_HIDDEN) {
        ViewCompat.offsetTopAndBottom(child, parentHeight);
    } else if (state == STATE_COLLAPSED) {
        ViewCompat.offsetTopAndBottom(child, collapsedOffset);
    } else if (state == STATE_DRAGGING || state == STATE_SETTLING) {
        ViewCompat.offsetTopAndBottom(child, savedTop - child.getTop());
    }

    //nestedScrollingChildRef = new WeakReference<>(findScrollingChild(child));
    return true;
}
 
Example 18
Source File: ShadowDrawable.java    From monero-wallet-android-app with MIT License 4 votes vote down vote up
public static void setShadowDrawable(View view, Drawable drawable) {
    view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    ViewCompat.setBackground(view, drawable);
}
 
Example 19
Source File: BottomNavigationItemView.java    From material-components-android with Apache License 2.0 4 votes vote down vote up
public void setItemBackground(@Nullable Drawable background) {
  if (background != null && background.getConstantState() != null) {
    background = background.getConstantState().newDrawable().mutate();
  }
  ViewCompat.setBackground(this, background);
}
 
Example 20
Source File: BottomSheetBehavior.java    From material-components-android with Apache License 2.0 4 votes vote down vote up
@Override
public boolean onLayoutChild(
    @NonNull CoordinatorLayout parent, @NonNull V child, int layoutDirection) {
  if (ViewCompat.getFitsSystemWindows(parent) && !ViewCompat.getFitsSystemWindows(child)) {
    child.setFitsSystemWindows(true);
  }

  if (viewRef == null) {
    // First layout with this behavior.
    peekHeightMin =
        parent.getResources().getDimensionPixelSize(R.dimen.design_bottom_sheet_peek_height_min);
    setSystemGestureInsets(parent);
    viewRef = new WeakReference<>(child);
    // Only set MaterialShapeDrawable as background if shapeTheming is enabled, otherwise will
    // default to android:background declared in styles or layout.
    if (shapeThemingEnabled && materialShapeDrawable != null) {
      ViewCompat.setBackground(child, materialShapeDrawable);
    }
    // Set elevation on MaterialShapeDrawable
    if (materialShapeDrawable != null) {
      // Use elevation attr if set on bottomsheet; otherwise, use elevation of child view.
      materialShapeDrawable.setElevation(
          elevation == -1 ? ViewCompat.getElevation(child) : elevation);
      // Update the material shape based on initial state.
      isShapeExpanded = state == STATE_EXPANDED;
      materialShapeDrawable.setInterpolation(isShapeExpanded ? 0f : 1f);
    }
    updateAccessibilityActions();
    if (ViewCompat.getImportantForAccessibility(child)
        == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
      ViewCompat.setImportantForAccessibility(child, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
    }
  }
  if (viewDragHelper == null) {
    viewDragHelper = ViewDragHelper.create(parent, dragCallback);
  }

  int savedTop = child.getTop();
  // First let the parent lay it out
  parent.onLayoutChild(child, layoutDirection);
  // Offset the bottom sheet
  parentWidth = parent.getWidth();
  parentHeight = parent.getHeight();
  fitToContentsOffset = Math.max(0, parentHeight - child.getHeight());
  calculateHalfExpandedOffset();
  calculateCollapsedOffset();

  if (state == STATE_EXPANDED) {
    ViewCompat.offsetTopAndBottom(child, getExpandedOffset());
  } else if (state == STATE_HALF_EXPANDED) {
    ViewCompat.offsetTopAndBottom(child, halfExpandedOffset);
  } else if (hideable && state == STATE_HIDDEN) {
    ViewCompat.offsetTopAndBottom(child, parentHeight);
  } else if (state == STATE_COLLAPSED) {
    ViewCompat.offsetTopAndBottom(child, collapsedOffset);
  } else if (state == STATE_DRAGGING || state == STATE_SETTLING) {
    ViewCompat.offsetTopAndBottom(child, savedTop - child.getTop());
  }

  nestedScrollingChildRef = new WeakReference<>(findScrollingChild(child));
  return true;
}