Example usage for android.graphics.drawable GradientDrawable setColor

List of usage examples for android.graphics.drawable GradientDrawable setColor

Introduction

In this page you can find the example usage for android.graphics.drawable GradientDrawable setColor.

Prototype

public void setColor(@Nullable ColorStateList colorStateList) 

Source Link

Document

Changes this drawable to use a single color state list instead of a gradient.

Usage

From source file:com.nickandjerry.dynamiclayoutinflator.DynamicLayoutInflator.java

@SuppressLint("NewApi")
private static void applyAttributes(View view, Map<String, String> attrs, ViewGroup parent) {
    if (viewRunnables == null)
        createViewRunnables();/*from w ww. j  av a 2  s.co  m*/
    ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
    int layoutRule;
    int marginLeft = 0, marginRight = 0, marginTop = 0, marginBottom = 0, paddingLeft = 0, paddingRight = 0,
            paddingTop = 0, paddingBottom = 0;
    boolean hasCornerRadius = false, hasCornerRadii = false;
    for (Map.Entry<String, String> entry : attrs.entrySet()) {
        String attr = entry.getKey();
        if (viewRunnables.containsKey(attr)) {
            viewRunnables.get(attr).apply(view, entry.getValue(), parent, attrs);
            continue;
        }
        if (attr.startsWith("cornerRadius")) {
            hasCornerRadius = true;
            hasCornerRadii = !attr.equals("cornerRadius");
            continue;
        }
        layoutRule = NO_LAYOUT_RULE;
        boolean layoutTarget = false;
        switch (attr) {
        case "id":
            String idValue = parseId(entry.getValue());
            if (parent != null) {
                DynamicLayoutInfo info = getDynamicLayoutInfo(parent);
                int newId = highestIdNumberUsed++;
                view.setId(newId);
                info.nameToIdNumber.put(idValue, newId);
            }
            break;
        case "width":
        case "layout_width":
            switch (entry.getValue()) {
            case "wrap_content":
                layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
                break;
            case "fill_parent":
            case "match_parent":
                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                break;
            default:
                layoutParams.width = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                        view.getResources().getDisplayMetrics(), parent, true);
                break;
            }
            break;
        case "height":
        case "layout_height":
            switch (entry.getValue()) {
            case "wrap_content":
                layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                break;
            case "fill_parent":
            case "match_parent":
                layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
                break;
            default:
                layoutParams.height = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                        view.getResources().getDisplayMetrics(), parent, false);
                break;
            }
            break;
        case "layout_gravity":
            if (parent != null && parent instanceof LinearLayout) {
                ((LinearLayout.LayoutParams) layoutParams).gravity = parseGravity(entry.getValue());
            } else if (parent != null && parent instanceof FrameLayout) {
                ((FrameLayout.LayoutParams) layoutParams).gravity = parseGravity(entry.getValue());
            }
            break;
        case "layout_weight":
            if (parent != null && parent instanceof LinearLayout) {
                ((LinearLayout.LayoutParams) layoutParams).weight = Float.parseFloat(entry.getValue());
            }
            break;
        case "layout_below":
            layoutRule = RelativeLayout.BELOW;
            layoutTarget = true;
            break;
        case "layout_above":
            layoutRule = RelativeLayout.ABOVE;
            layoutTarget = true;
            break;
        case "layout_toLeftOf":
            layoutRule = RelativeLayout.LEFT_OF;
            layoutTarget = true;
            break;
        case "layout_toRightOf":
            layoutRule = RelativeLayout.RIGHT_OF;
            layoutTarget = true;
            break;
        case "layout_alignBottom":
            layoutRule = RelativeLayout.ALIGN_BOTTOM;
            layoutTarget = true;
            break;
        case "layout_alignTop":
            layoutRule = RelativeLayout.ALIGN_TOP;
            layoutTarget = true;
            break;
        case "layout_alignLeft":
        case "layout_alignStart":
            layoutRule = RelativeLayout.ALIGN_LEFT;
            layoutTarget = true;
            break;
        case "layout_alignRight":
        case "layout_alignEnd":
            layoutRule = RelativeLayout.ALIGN_RIGHT;
            layoutTarget = true;
            break;
        case "layout_alignParentBottom":
            layoutRule = RelativeLayout.ALIGN_PARENT_BOTTOM;
            break;
        case "layout_alignParentTop":
            layoutRule = RelativeLayout.ALIGN_PARENT_TOP;
            break;
        case "layout_alignParentLeft":
        case "layout_alignParentStart":
            layoutRule = RelativeLayout.ALIGN_PARENT_LEFT;
            break;
        case "layout_alignParentRight":
        case "layout_alignParentEnd":
            layoutRule = RelativeLayout.ALIGN_PARENT_RIGHT;
            break;
        case "layout_centerHorizontal":
            layoutRule = RelativeLayout.CENTER_HORIZONTAL;
            break;
        case "layout_centerVertical":
            layoutRule = RelativeLayout.CENTER_VERTICAL;
            break;
        case "layout_centerInParent":
            layoutRule = RelativeLayout.CENTER_IN_PARENT;
            break;
        case "layout_margin":
            marginLeft = marginRight = marginTop = marginBottom = DimensionConverter
                    .stringToDimensionPixelSize(entry.getValue(), view.getResources().getDisplayMetrics());
            break;
        case "layout_marginLeft":
            marginLeft = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                    view.getResources().getDisplayMetrics(), parent, true);
            break;
        case "layout_marginTop":
            marginTop = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                    view.getResources().getDisplayMetrics(), parent, false);
            break;
        case "layout_marginRight":
            marginRight = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                    view.getResources().getDisplayMetrics(), parent, true);
            break;
        case "layout_marginBottom":
            marginBottom = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                    view.getResources().getDisplayMetrics(), parent, false);
            break;
        case "padding":
            paddingBottom = paddingLeft = paddingRight = paddingTop = DimensionConverter
                    .stringToDimensionPixelSize(entry.getValue(), view.getResources().getDisplayMetrics());
            break;
        case "paddingLeft":
            paddingLeft = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                    view.getResources().getDisplayMetrics());
            break;
        case "paddingTop":
            paddingTop = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                    view.getResources().getDisplayMetrics());
            break;
        case "paddingRight":
            paddingRight = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                    view.getResources().getDisplayMetrics());
            break;
        case "paddingBottom":
            paddingBottom = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                    view.getResources().getDisplayMetrics());
            break;

        }
        if (layoutRule != NO_LAYOUT_RULE && parent instanceof RelativeLayout) {
            if (layoutTarget) {
                int anchor = idNumFromIdString(parent, parseId(entry.getValue()));
                ((RelativeLayout.LayoutParams) layoutParams).addRule(layoutRule, anchor);
            } else if (entry.getValue().equals("true")) {
                ((RelativeLayout.LayoutParams) layoutParams).addRule(layoutRule);
            }
        }
    }
    // TODO: this is a giant mess; come up with a simpler way of deciding what to draw for the background
    if (attrs.containsKey("background") || attrs.containsKey("borderColor")) {
        String bgValue = attrs.containsKey("background") ? attrs.get("background") : null;
        if (bgValue != null && bgValue.startsWith("@drawable/")) {
            view.setBackground(getDrawableByName(view, bgValue));
        } else if (bgValue == null || bgValue.startsWith("#") || bgValue.startsWith("@color")) {
            if (view instanceof Button || attrs.containsKey("pressedColor")) {
                int bgColor = parseColor(view, bgValue == null ? "#00000000" : bgValue);
                int pressedColor;
                if (attrs.containsKey("pressedColor")) {
                    pressedColor = parseColor(view, attrs.get("pressedColor"));
                } else {
                    pressedColor = adjustBrightness(bgColor, 0.9f);
                }
                GradientDrawable gd = new GradientDrawable();
                gd.setColor(bgColor);
                GradientDrawable pressedGd = new GradientDrawable();
                pressedGd.setColor(pressedColor);
                if (hasCornerRadii) {
                    float radii[] = new float[8];
                    for (int i = 0; i < CORNERS.length; i++) {
                        String corner = CORNERS[i];
                        if (attrs.containsKey("cornerRadius" + corner)) {
                            radii[i * 2] = radii[i * 2 + 1] = DimensionConverter.stringToDimension(
                                    attrs.get("cornerRadius" + corner),
                                    view.getResources().getDisplayMetrics());
                        }
                        gd.setCornerRadii(radii);
                        pressedGd.setCornerRadii(radii);
                    }
                } else if (hasCornerRadius) {
                    float cornerRadius = DimensionConverter.stringToDimension(attrs.get("cornerRadius"),
                            view.getResources().getDisplayMetrics());
                    gd.setCornerRadius(cornerRadius);
                    pressedGd.setCornerRadius(cornerRadius);
                }
                if (attrs.containsKey("borderColor")) {
                    String borderWidth = "1dp";
                    if (attrs.containsKey("borderWidth")) {
                        borderWidth = attrs.get("borderWidth");
                    }
                    int borderWidthPx = DimensionConverter.stringToDimensionPixelSize(borderWidth,
                            view.getResources().getDisplayMetrics());
                    gd.setStroke(borderWidthPx, parseColor(view, attrs.get("borderColor")));
                    pressedGd.setStroke(borderWidthPx, parseColor(view, attrs.get("borderColor")));
                }
                StateListDrawable selector = new StateListDrawable();
                selector.addState(new int[] { android.R.attr.state_pressed }, pressedGd);
                selector.addState(new int[] {}, gd);
                view.setBackground(selector);
                getDynamicLayoutInfo(view).bgDrawable = gd;
            } else if (hasCornerRadius || attrs.containsKey("borderColor")) {
                GradientDrawable gd = new GradientDrawable();
                int bgColor = parseColor(view, bgValue == null ? "#00000000" : bgValue);
                gd.setColor(bgColor);
                if (hasCornerRadii) {
                    float radii[] = new float[8];
                    for (int i = 0; i < CORNERS.length; i++) {
                        String corner = CORNERS[i];
                        if (attrs.containsKey("cornerRadius" + corner)) {
                            radii[i * 2] = radii[i * 2 + 1] = DimensionConverter.stringToDimension(
                                    attrs.get("cornerRadius" + corner),
                                    view.getResources().getDisplayMetrics());
                        }
                        gd.setCornerRadii(radii);
                    }
                } else if (hasCornerRadius) {
                    float cornerRadius = DimensionConverter.stringToDimension(attrs.get("cornerRadius"),
                            view.getResources().getDisplayMetrics());
                    gd.setCornerRadius(cornerRadius);
                }
                if (attrs.containsKey("borderColor")) {
                    String borderWidth = "1dp";
                    if (attrs.containsKey("borderWidth")) {
                        borderWidth = attrs.get("borderWidth");
                    }
                    gd.setStroke(
                            DimensionConverter.stringToDimensionPixelSize(borderWidth,
                                    view.getResources().getDisplayMetrics()),
                            parseColor(view, attrs.get("borderColor")));
                }
                view.setBackground(gd);
                getDynamicLayoutInfo(view).bgDrawable = gd;
            } else {
                view.setBackgroundColor(parseColor(view, bgValue));
            }
        }
    }

    if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
        ((ViewGroup.MarginLayoutParams) layoutParams).setMargins(marginLeft, marginTop, marginRight,
                marginBottom);
    }
    view.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
    view.setLayoutParams(layoutParams);
}

From source file:android.support.design.widget.FloatingActionButtonImpl.java

GradientDrawable createShapeDrawable() {
    GradientDrawable d = newGradientDrawableForShape();
    d.setShape(GradientDrawable.OVAL);
    d.setColor(Color.WHITE);
    return d;
}

From source file:com.karthikb351.vitinfo2.fragment.timetable.TimetableListAdapter.java

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
@Override/*  w  ww.  j  av  a2  s .com*/
public void onBindViewHolder(TimeTableViewHolder timeTableViewHolder, int position) {

    int attendancePercentage = 0;
    String startTime;
    String endTime;

    if (courseTimingPairs.get(position).first.getAttendance().isSupported()) {
        attendancePercentage = courseTimingPairs.get(position).first.getAttendance().getAttendancePercentage();
    }
    try {
        startTime = DateTimeCalender.parseISO8601Time(courseTimingPairs.get(position).second.getStartTime());
        endTime = DateTimeCalender.parseISO8601Time(courseTimingPairs.get(position).second.getEndTime());
    } catch (ParseException ex) {
        ex.printStackTrace();
        startTime = courseTimingPairs.get(position).second.getStartTime();
        endTime = courseTimingPairs.get(position).second.getEndTime();
    }

    timeTableViewHolder.courseCode.setText(courseTimingPairs.get(position).first.getCourseCode());
    timeTableViewHolder.courseName.setText(courseTimingPairs.get(position).first.getCourseTitle());
    timeTableViewHolder.venue.setText(courseTimingPairs.get(position).first.getVenue());
    timeTableViewHolder.slot.setText(courseTimingPairs.get(position).first.getSlot());
    timeTableViewHolder.attendance.setText(Integer.toString(attendancePercentage));
    timeTableViewHolder.slotTiming
            .setText(context.getString(R.string.timetable_course_slot_timing, startTime, endTime));
    timeTableViewHolder.progressBarAttendance.setProgress(attendancePercentage);

    int sdk = android.os.Build.VERSION.SDK_INT;
    int bgColor = getAttendanceColor(attendancePercentage);

    timeTableViewHolder.progressBarAttendance.getProgressDrawable().setColorFilter(bgColor,
            PorterDuff.Mode.SRC_IN);
    GradientDrawable txt_bgShape;
    txt_bgShape = (GradientDrawable) timeTableViewHolder.attendance.getBackground();
    txt_bgShape.setColor(bgColor);

    if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
        timeTableViewHolder.attendance.setBackgroundDrawable(txt_bgShape);
    } else {
        timeTableViewHolder.attendance.setBackground(txt_bgShape);
    }
}

From source file:im.vector.view.UnreadCounterBadgeView.java

/**
 * Update the badge value and its status
 *
 * @param text   the new text value//from w  ww .j  av a2  s  . c  o m
 * @param status the new status
 */
public void updateText(String text, @Status int status) {
    if (!TextUtils.isEmpty(text)) {
        mCounterTextView.setText(text);

        setVisibility(View.VISIBLE);
        GradientDrawable shape = new GradientDrawable();
        shape.setShape(GradientDrawable.RECTANGLE);
        shape.setCornerRadius(100);
        if (status == HIGHLIGHTED) {
            shape.setColor(ContextCompat.getColor(getContext(), R.color.vector_fuchsia_color));
        } else if (status == NOTIFIED) {
            shape.setColor(ContextCompat.getColor(getContext(), R.color.vector_green_color));
        } else { //if (status == DEFAULT)
            shape.setColor(ContextCompat.getColor(getContext(), R.color.vector_silver_color));
        }
        mParentView.setBackground(shape);
    } else {
        setVisibility(View.GONE);
    }
}

From source file:com.adkdevelopment.e_contact.DetailFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.detail_fragment_task, container, false);
    mUnbinder = ButterKnife.bind(this, rootView);

    // to prevent multiple calls to getContext()
    Context context = getContext();

    Intent intent = getActivity().getIntent();
    TaskItem newsItem;//from   w  ww .  j a  v  a 2s.c  o  m

    if (intent.hasExtra(TaskItem.TASKITEM)) {

        newsItem = intent.getParcelableExtra(TaskItem.TASKITEM);

        // Time parsing and creating a nice textual version (should be changed to Calendar)
        String dateCreated = Utilities.getFormattedDate(newsItem.getCreated());
        String dateRegistered = Utilities.getFormattedDate(newsItem.getRegistered());
        String dateAssigned = Utilities.getFormattedDate(newsItem.getAssigned());

        mTaskTitleText.setText(Utilities.getType(context, newsItem.getType()));
        mTaskStatus.setText(Utilities.getStatus(context, newsItem.getStatus()));

        // sets color of a status TextView shape according to the schema
        GradientDrawable gradientDrawable = (GradientDrawable) mTaskStatus.getBackground();
        gradientDrawable.setColor(Utilities.getBackgroundColor(context, newsItem.getStatus()));

        mTaskCreatedDate.setText(dateCreated);
        mTaskRegisteredDate.setText(dateRegistered);
        mTaskAssignedDate.setText(dateAssigned);
        mTaskResponsibleName.setText(newsItem.getResponsible());
        mTaskDescription.setText(Html.fromHtml(newsItem.getDescription()));

        Cursor cursor = context.getContentResolver().query(PhotosColumns.CONTENT_URI, null,
                PhotosColumns.TASK_ID + " LIKE ?", new String[] { "" + newsItem.getDatabaseId() }, null);

        if (cursor != null) {
            List<String> photos = new ArrayList<>(cursor.getCount());

            while (cursor.moveToNext()) {
                photos.add(cursor.getString(cursor.getColumnIndex(PhotosColumns.URL)));
            }
            cursor.close();
            newsItem.setPhoto(photos);
        }

    } else {
        // If there is no outside intent - fetch example photos
        List<String> dummyPhotos = new ArrayList<>();
        dummyPhotos.addAll(Arrays.asList(getResources().getStringArray(R.array.task_image_links)));

        newsItem = new TaskItem();
        newsItem.setPhoto(dummyPhotos);
    }

    // To boost performance as we know that size won't change
    mRecyclerView.setHasFixedSize(true);

    // Horizontal LayoutManager
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context, RecyclerView.HORIZONTAL, false);

    mRecyclerView.setLayoutManager(layoutManager);

    // Adapter with data about different activities
    PhotoAdapter photoAdapter = new PhotoAdapter(newsItem.getPhoto(), context, this);
    mRecyclerView.setAdapter(photoAdapter);

    return rootView;
}

From source file:com.esri.android.ecologicalmarineunitexplorer.watercolumn.WaterColumnFragment.java

private StateListDrawable buildStateList(int emuName) {
    StateListDrawable stateListDrawable = new StateListDrawable();

    GradientDrawable defaultShape = new GradientDrawable();
    int color = Color.parseColor(EmuHelper.getColorForEMUCluster(getContext(), emuName));
    defaultShape.setColor(color);

    GradientDrawable selectedPressShape = new GradientDrawable();
    selectedPressShape.setColor(color);/* ww  w.j  av  a2  s.  c  om*/
    selectedPressShape.setStroke(5, Color.parseColor("#f4f442"));

    stateListDrawable.addState(new int[] { android.R.attr.state_pressed }, selectedPressShape);
    stateListDrawable.addState(new int[] { android.R.attr.state_selected }, selectedPressShape);
    stateListDrawable.addState(new int[] { android.R.attr.state_enabled }, defaultShape);

    return stateListDrawable;
}

From source file:de.grobox.liberario.ui.LineView.java

public void setLine(Line line) {
    if (line.product != null) {
        Drawable drawable = ContextCompat.getDrawable(getContext(), getDrawableForProduct(line.product));
        ui.product.setImageDrawable(drawable);
    } else {/*from  w ww  .  j  av a  2s.  co m*/
        ui.product.setVisibility(GONE);
    }

    ui.label.setText(line.label);

    if (line.style != null) {
        GradientDrawable box = (GradientDrawable) ui.box.getBackground();

        if (box != null) {
            // change color and mutate before to not share state with other instances
            box.mutate();
            box.setColor(line.style.backgroundColor);
        }
        ui.label.setTextColor(line.style.foregroundColor);
        ui.product.setColorFilter(line.style.foregroundColor);
    }
}

From source file:io.github.runassudo.ptoffline.ui.LineView.java

public void setLine(Line line) {
    if (line.product != null) {
        Drawable drawable = ContextCompat.getDrawable(getContext(),
                TransportrUtils.getDrawableForProduct(line.product));
        ui.product.setImageDrawable(drawable);
    } else {/*ww  w . j a  va  2 s .c  om*/
        ui.product.setVisibility(GONE);
    }

    ui.label.setText(line.label);

    if (line.style != null) {
        GradientDrawable box = (GradientDrawable) ui.box.getBackground();

        if (box != null) {
            // change color and mutate before to not share state with other instances
            box.mutate();
            box.setColor(line.style.backgroundColor);
        }
        ui.label.setTextColor(line.style.foregroundColor);
        ui.product.setColorFilter(line.style.foregroundColor);
    }
}

From source file:ro.expectations.expenses.ui.accounts.AccountsAdapter.java

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    mCursor.moveToPosition(position);/*from  w ww.j  ava 2 s  .  c  o  m*/

    // Set the row background
    ListHelper.setItemBackground(mContext, holder.itemView, isItemSelected(position),
            holder.mAccountIconBackground, holder.mSelectedIconBackground);

    // Set the icon
    String type = mCursor.getString(mCursor.getColumnIndex(ExpensesContract.Accounts.TYPE));
    AccountType accountType = AccountType.valueOf(type);
    if (accountType == AccountType.CREDIT_CARD || accountType == AccountType.DEBIT_CARD) {
        String issuer = mCursor.getString(mCursor.getColumnIndex(ExpensesContract.Accounts.SUBTYPE));
        CardIssuer cardIssuer;
        if (issuer == null) {
            cardIssuer = CardIssuer.OTHER;
        } else {
            try {
                cardIssuer = CardIssuer.valueOf(issuer);
            } catch (final IllegalArgumentException ex) {
                cardIssuer = CardIssuer.OTHER;
            }
        }
        holder.mAccountIcon
                .setImageDrawable(DrawableHelper.tint(mContext, cardIssuer.iconId, R.color.colorWhite));
    } else if (accountType == AccountType.ELECTRONIC) {
        String paymentType = mCursor.getString(mCursor.getColumnIndex(ExpensesContract.Accounts.SUBTYPE));
        ElectronicPaymentType electronicPaymentType;
        if (paymentType == null) {
            electronicPaymentType = ElectronicPaymentType.OTHER;
        } else {
            try {
                electronicPaymentType = ElectronicPaymentType.valueOf(paymentType);
            } catch (IllegalArgumentException ex) {
                electronicPaymentType = ElectronicPaymentType.OTHER;
            }
        }
        holder.mAccountIcon.setImageDrawable(
                DrawableHelper.tint(mContext, electronicPaymentType.iconId, R.color.colorWhite));
    } else {
        holder.mAccountIcon
                .setImageDrawable(DrawableHelper.tint(mContext, accountType.iconId, R.color.colorWhite));
    }

    // Set the icon background color
    GradientDrawable bgShape = (GradientDrawable) holder.mAccountIconBackground.getBackground();
    bgShape.setColor(0xFF000000 | ContextCompat.getColor(mContext, accountType.colorId));

    // Set the description
    holder.mAccountDescription.setText(accountType.titleId);

    // Set the title
    String title = mCursor.getString(mCursor.getColumnIndex(ExpensesContract.Accounts.TITLE));
    holder.mAccountTitle.setText(title);

    // Set the date
    long now = System.currentTimeMillis();
    long lastTransactionAt = mCursor
            .getLong(mCursor.getColumnIndex(ExpensesContract.Accounts.LAST_TRANSACTION_AT));
    if (lastTransactionAt == 0) {
        lastTransactionAt = mCursor.getLong(mCursor.getColumnIndex(ExpensesContract.Accounts.CREATED_AT));
    }
    holder.mAccountLastTransactionAt
            .setText(DateUtils.getRelativeTimeSpanString(lastTransactionAt, now, DateUtils.DAY_IN_MILLIS));

    // Set the account balance
    double balance = NumberUtils.roundToTwoPlaces(
            mCursor.getLong(mCursor.getColumnIndex(ExpensesContract.Accounts.BALANCE)) / 100.0);
    String currencyCode = mCursor.getString(mCursor.getColumnIndex(ExpensesContract.Accounts.CURRENCY));
    Currency currency = Currency.getInstance(currencyCode);
    NumberFormat format = NumberFormat.getCurrencyInstance();
    format.setCurrency(currency);
    format.setMaximumFractionDigits(currency.getDefaultFractionDigits());
    holder.mAccountBalance.setText(format.format(balance));
    if (balance > 0) {
        holder.mAccountBalance.setTextColor(ContextCompat.getColor(mContext, R.color.colorGreen700));
    } else if (balance < 0) {
        holder.mAccountBalance.setTextColor(ContextCompat.getColor(mContext, R.color.colorRed700));
    }
}

From source file:com.fuzz.emptyhusk.prefab.ProportionalImageCellGenerator.java

@Override
public void onBindChild(@NonNull View child, @NonNull CutoutViewLayoutParams lp, @Nullable View originator) {
    child.setBackgroundResource(lp.cellBackgroundId);
    if (originator != null) {
        rvChildLength = originator.getHeight();
        if (originator.getParent() instanceof ViewGroup) {
            rvLength = ((ViewGroup) originator.getParent()).getHeight();
        }//  w ww  .j  a  v  a2s . co  m
    }
    if (child instanceof ImageView) {
        GradientDrawable elongated = new GradientDrawable();
        elongated.setShape(GradientDrawable.RECTANGLE);

        int accent = ContextCompat.getColor(child.getContext(), R.color.transparentColorAccent);

        float fractionOfParent = rvLength * 1.0f / rvChildLength;

        elongated.setColor(accent);
        float proposedLength = fractionOfParent * lp.perpendicularLength;
        elongated.setSize(lp.perpendicularLength, (int) proposedLength);

        ((ImageView) child).setImageDrawable(elongated);
    }
}