|
1 /* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- |
|
2 * This Source Code Form is subject to the terms of the Mozilla Public |
|
3 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
5 |
|
6 package org.mozilla.gecko.home; |
|
7 |
|
8 import android.content.Context; |
|
9 import android.content.res.TypedArray; |
|
10 import android.graphics.Canvas; |
|
11 import android.graphics.LinearGradient; |
|
12 import android.graphics.Shader; |
|
13 import android.graphics.drawable.Drawable; |
|
14 import android.util.AttributeSet; |
|
15 import android.widget.TextView; |
|
16 |
|
17 import org.mozilla.gecko.R; |
|
18 |
|
19 /** |
|
20 * FadedTextView fades the ends of the text by fadeWidth amount, |
|
21 * if the text is too long and requires an ellipsis. |
|
22 */ |
|
23 public class FadedTextView extends TextView { |
|
24 |
|
25 // Width of the fade effect from end of the view. |
|
26 private int mFadeWidth; |
|
27 |
|
28 // Padding for compound drawables. |
|
29 private int mCompoundPadding; |
|
30 |
|
31 public FadedTextView(Context context) { |
|
32 this(context, null); |
|
33 } |
|
34 |
|
35 public FadedTextView(Context context, AttributeSet attrs) { |
|
36 this(context, attrs, android.R.attr.textViewStyle); |
|
37 } |
|
38 |
|
39 public FadedTextView(Context context, AttributeSet attrs, int defStyle) { |
|
40 super(context, attrs, defStyle); |
|
41 |
|
42 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FadedTextView); |
|
43 mFadeWidth = a.getDimensionPixelSize(R.styleable.FadedTextView_fadeWidth, 0); |
|
44 a.recycle(); |
|
45 |
|
46 mCompoundPadding = getCompoundDrawablePadding(); |
|
47 } |
|
48 |
|
49 /** |
|
50 * {@inheritDoc} |
|
51 */ |
|
52 @Override |
|
53 public void onDraw(Canvas canvas) { |
|
54 int width = getMeasuredWidth(); |
|
55 |
|
56 // Layout doesn't return a proper width for getWidth(). |
|
57 // Instead check the width of the first line, as we've restricted to just one line. |
|
58 if (getLayout().getLineWidth(0) > width) { |
|
59 final Drawable leftDrawable = getCompoundDrawables()[0]; |
|
60 int drawableWidth = 0; |
|
61 if (leftDrawable != null) { |
|
62 drawableWidth = leftDrawable.getIntrinsicWidth() + mCompoundPadding; |
|
63 width -= drawableWidth; |
|
64 } |
|
65 |
|
66 int color = getCurrentTextColor(); |
|
67 float stop = ((float) (width - mFadeWidth) / (float) width); |
|
68 LinearGradient gradient = new LinearGradient(0, 0, width, 0, |
|
69 new int[] { color, color, 0x0 }, |
|
70 new float[] { 0, stop, 1.0f - (drawableWidth / width) }, |
|
71 Shader.TileMode.CLAMP); |
|
72 getPaint().setShader(gradient); |
|
73 } else { |
|
74 getPaint().setShader(null); |
|
75 } |
|
76 |
|
77 // Do a default draw. |
|
78 super.onDraw(canvas); |
|
79 } |
|
80 } |