When I include the below XML to layout file, I can see the below image. If you see it, you could realize that the TextView has top and bottom space.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="E1"
android:background="#ff00ff00"/>
I wish to remove the space. How to remove it? What is it called?
If anyone has clue.. please let me know. Thanks in advance.
Try android:includeFontPadding="false" to see if it helps. In my experience that will help a little bit, but there's no way of reducing the TextView dimensions to the exact pixel-perfect text size.
The only alternative, which may or may not give better results, is to cheat a bit and hard-wire the dimensions to match the text size, e.g. "24sp" instead of "wrap_content" for the height.
I had the same problem. Attribute android:includeFontPadding="false" does not work for me. I've solved this problem in this way:
public class TextViewWithoutPaddings extends TextView {
private final Paint mPaint = new Paint();
private final Rect mBounds = new Rect();
public TextViewWithoutPaddings(Context context) {
super(context);
}
public TextViewWithoutPaddings(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TextViewWithoutPaddings(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
protected void onDraw(#NonNull Canvas canvas) {
final String text = calculateTextParams();
final int left = mBounds.left;
final int bottom = mBounds.bottom;
mBounds.offset(-mBounds.left, -mBounds.top);
mPaint.setAntiAlias(true);
mPaint.setColor(getCurrentTextColor());
canvas.drawText(text, -left, mBounds.bottom - bottom, mPaint);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
calculateTextParams();
setMeasuredDimension(mBounds.width() + 1, -mBounds.top + 1);
}
private String calculateTextParams() {
final String text = getText().toString();
final int textLength = text.length();
mPaint.setTextSize(getTextSize());
mPaint.getTextBounds(text, 0, textLength, mBounds);
if (textLength == 0) {
mBounds.right = mBounds.left;
}
return text;
}
}
android:includeFontPadding="false" is pretty good but it does not get it precisely. sometimes you want border line accuracy so you can figure it out yourself by applying negative margins:
try setting your bottom and top margins to a negative value.
something like this:
android:layout_marginTop="-5dp"
android:layout_marginBottom="-5dp"
adjust the values accordingly.
This is the code that saved our day. It was adapted using mono C# code from maksimko:
public class TopAlignedTextView extends TextView {
public TopAlignedTextView(Context context) {
super(context);
}
/*This is where the magic happens*/
#Override
protected void onDraw(Canvas canvas){
float offset = getTextSize() - getLineHeight();
canvas.translate(0, offset);
super.onDraw(canvas);
}
}
Still had to play around with textView.setIncludeFontPadding(false) because we were aligning TextViews with different font sizes.
I faced the same problem.
Here's a good answer: How to align the text to top of TextView?
But code is little unfinished and don't support all font sizes. Change the line
int additionalPadding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, getContext().getResources().getDisplayMetrics());
to
int additionalPadding = getTextSize() - getLineHeight();
Complete C# code (mono) removes top offset:
public class TextControl : TextView {
public TextControl (Context context) : base (context)
{
SetIncludeFontPadding (false);
Gravity = GravityFlags.Top;
}
protected override void OnDraw (Android.Graphics.Canvas canvas)
{
if (base.Layout == null)
return;
Paint.Color = new Android.Graphics.Color (CurrentTextColor);
Paint.DrawableState = GetDrawableState ();
canvas.Save ();
var offset = TextSize - LineHeight;
canvas.Translate (0, offset);
base.Layout.Draw (canvas);
canvas.Restore ();
}
}
Just wanted to add to DynamicMind's answer that the reason why you see spacing around your TextViews is padding in 9-patch backgrounds they use by default.
9-patch technology allows you to specify a content area which is, effectively, padding. That padding is used unless you set the view's padding explicitly. E.g., when you programmatically set a 9-patch background to a view which had paddings set, they are overridden. And vise-versa, if you set paddings they override what was set by 9-patch background.
Unfortunately, in the XML layout it's not possible to determine the order of these operations. I think just removing the background from your TextViews would help:
android:background="#null"
public class TopAlignedTextView extends TextView {
public TopAlignedTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TopAlignedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs);
setIncludeFontPadding(false); //remove the font padding
setGravity(getGravity() | Gravity.TOP);
}
#Override
protected void onDraw(Canvas canvas) {
TextPaint textPaint = getPaint();
textPaint.setColor(getCurrentTextColor());
textPaint.drawableState = getDrawableState();
canvas.save();
//remove extra font padding
int yOffset = getHeight() - getBaseline();
canvas.translate(0, - yOffset / 2);
if (getLayout() != null) {
getLayout().draw(canvas);
}
canvas.restore();
}
}
Modified this answer a little bit to use kotlin class and extend AppCompatTextView, trimming vertical padding.
It allows setting android:fontFamily. Method calculateTextParams() moved from onDraw() for performance. Not tested for multiple lines of text:
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
class NoPaddingTextView : AppCompatTextView
{
private val boundsRect = Rect()
private val textParams = calculateTextParams()
constructor(context : Context?)
: super(context)
constructor(context : Context?, attrs : AttributeSet?)
: super(context, attrs)
constructor(context : Context?, attrs : AttributeSet?, defStyleAttr : Int)
: super(context, attrs, defStyleAttr)
override fun onDraw(canvas : Canvas)
{
with(boundsRect) {
paint.isAntiAlias = true
paint.color = currentTextColor
canvas.drawText(textParams,
-left.toFloat(),
(-top - bottom).toFloat(),
paint)
}
}
override fun onMeasure(widthMeasureSpec : Int, heightMeasureSpec : Int)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
calculateTextParams()
setMeasuredDimension(boundsRect.width() + 1, -boundsRect.top + 1)
}
private fun calculateTextParams() : String
{
return text.toString()
.also {text ->
text.length.let {textLength ->
paint.textSize = textSize
paint.getTextBounds(text, 0, textLength, boundsRect)
if(textLength == 0) boundsRect.right = boundsRect.left
}
}
}
}
Have you defined a layout margin?
For example:
android:layout_marginTop="5dp"
Otherwise, if your text view is wrapped inside a LinearLayout or other container, then that cold have either padding or a margin too.
android:background="#android:drawable/editbox_background"
use it according to you change it that you want editbox_background.
because android provide some build in background like above code choose according to your requirement.
May be it is help full to you.
Inside a LinearLayout the default padding might be an issue. Try setting it to 0dp. It worked for me.
The answer of TopAlignedTextView code:TopAlignedTextView#GitHub
use it by layout:
<com.github.captain_miao.view.TopAlignedTextView
android:id="#+id/text_a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:text="#string/text_demo_a"
/>
My way for fixing this is pretty hacky, but I managed to get the text to sit where I wanted by setting the height of the text view as static and fiddling with it until it just barely fit the text. In my case, the font style I was using had a height of 64sp so I set the height of my textview to 50sp and it worked okay. I also had to set foreground_gravity to bottom.
android:includeFontPadding="false"
Related
I am trying to use Autosizing TextViews in a RecyclerView, but when I scroll a few times the text gets so small that it's obviously not working properly.
Example of my TextView:
<android.support.v7.widget.AppCompatTextView
android:id="#+id/textview_unit_title"
android:layout_width="#dimen/tile_image_size"
android:layout_height="wrap_content"
android:maxLines="2"
android:textSize="#dimen/medium_size"
android:textColor="#color/color_text"
android:paddingTop="#dimen/padding_title"
android:layout_marginRight="2dp"
android:layout_marginEnd="2dp"
app:autoSizeMaxTextSize="#dimen/style_medium"
app:autoSizeTextType="uniform"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toRightOf="#id/imageview_unit_icon"
app:layout_constraintTop_toTopOf="parent"/>
Should I update this scaling somewhere else programmatically or is there another solution?
The issue I've seen with this is that setting your view height to be wrap_content allows the text size to get smaller, but the text will never get bigger again. This is why the documentation recommends to not use wrap_content for the view size. However, I've found that if you turn off the auto-resizing, set the text size to whatever the max is, then re-enable auto-resizing, the text size resets to the largest size and scales down as necessary.
So my view in XML would look like:
<android.support.v7.widget.AppCompatTextView
android:id="#+id/text_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:textAllCaps="true"
android:textColor="#android:color/white"
android:textSize="42sp"
app:autoSizeMinTextSize="26dp"
app:autoSizeMaxTextSize="42dp"
app:autoSizeTextType="none"/>
Then in my ViewHolder when I bind my text to the view:
TextView title = view.findViewById(R.id.text_title);
String titleValue = "Some Title Value";
// Turn off auto-sizing text.
TextViewCompat.setAutoSizeTextTypeWithDefaults(title,
TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE);
// Bump text size back up to the max value.
title.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 42);
// Set your text as normal.
title.setText(titleValue);
// Post a runnable to re-enable auto-sizing text so that it occurs
// after the view is laid out and measured at max text size.
title.post(new Runnable() {
#Override
public void run() {
TextViewCompat
.setAutoSizeTextTypeUniformWithConfiguration(title,
26, 42, 1, TypedValue.COMPLEX_UNIT_DIP);
}
});
Autosizing TextViews
Android 8.0 (API level 26) allows you to instruct a TextView to let the text size expand or contract automatically to fill its layout based on the TextView's characteristics and boundaries.
Note: If you set autosizing in an XML file, it is not recommended to
use the value "wrap_content" for the layout_width or layout_height
attributes of a TextView. It may produce unexpected results.
You should bound height
android:layout_height="30dp"
Pavel Haluza's answer's approach was great. However, it didn't work, probably because he missed a line setTextSize(TypedValue.COMPLEX_UNIT_PX, maxTextSize);.
Here is my updated version:
public class MyTextView extends AppCompatTextView {
private int minTextSize;
private int maxTextSize;
private int granularity;
public MyTextView(Context context) {
super(context);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
minTextSize = TextViewCompat.getAutoSizeMinTextSize(this);
maxTextSize = TextViewCompat.getAutoSizeMaxTextSize(this);
granularity = Math.max(1, TextViewCompat.getAutoSizeStepGranularity(this));
}
#Override
public void setText(CharSequence text, BufferType type) {
// this method is called on every setText
disableAutoSizing();
setTextSize(TypedValue.COMPLEX_UNIT_PX, maxTextSize);
super.setText(text, type);
post(this::enableAutoSizing); // enable after the view is laid out and measured at max text size
}
private void disableAutoSizing() {
TextViewCompat.setAutoSizeTextTypeWithDefaults(this, TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE);
}
private void enableAutoSizing() {
TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(this,
minTextSize, maxTextSize, granularity, TypedValue.COMPLEX_UNIT_PX);
}}
I packaged Michael Celey's answer into a class. The parameters app:autoSizeMinTextSize, app:autoSizeMaxTextSize, app:autoSizeTextType are taken from xml.
public class AutosizingTextView extends AppCompatTextView {
private int minTextSize;
private int maxTextSize;
private int granularity;
public AutosizingTextView(Context context) {
super(context);
init();
}
public AutosizingTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public AutosizingTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
minTextSize = TextViewCompat.getAutoSizeMinTextSize(this);
maxTextSize = TextViewCompat.getAutoSizeMaxTextSize(this);
granularity = TextViewCompat.getAutoSizeStepGranularity(this);
}
#Override
public void setText(CharSequence text, BufferType type) {
// this method is called on every setText
disableAutosizing();
super.setText(text, type);
post(this::enableAutosizing); // enable after the view is laid out and measured at max text size
}
private void disableAutosizing() {
TextViewCompat.setAutoSizeTextTypeWithDefaults(this, TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE);
}
private void enableAutosizing() {
TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(this,
minTextSize, maxTextSize, granularity, TypedValue.COMPLEX_UNIT_PX);
}
}```
the above solutions didn't work for me so here's mine
public class MyTextView extends AppCompatTextView {
...
#Override
public final void setText(CharSequence text, BufferType type) {
// work around stupid auto size text not *growing* the font size we re binding in a RecyclerView if previous bind caused a small font
int minTextSize = 0, maxTextSize = 0, granularity = 0;
boolean doHack = TextViewCompat.getAutoSizeTextType(this) != TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE;
if (doHack) {
minTextSize = TextViewCompat.getAutoSizeMinTextSize(this);
maxTextSize = TextViewCompat.getAutoSizeMaxTextSize(this);
if (minTextSize <= 0 || maxTextSize <= minTextSize) { // better than validateAndSetAutoSizeTextTypeUniformConfiguration crashing
if (BuildConfig.DEBUG)
throw new AssertionError("fix ya layout");
doHack = false;
} else {
granularity = TextViewCompat.getAutoSizeStepGranularity(this);
if (granularity < 0)
granularity = 1; // need this else setAutoSizeTextTypeUniformWithConfiguration barfs. TextView.UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE = 1.
// make the TextView have 0 size so setAutoSizeTextTypeUniformWithConfiguration won't do calculations until after a layout pass using maxSize
TextViewCompat.setAutoSizeTextTypeWithDefaults(this, TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE);
setTextSize(TypedValue.COMPLEX_UNIT_PX, maxTextSize);
measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.EXACTLY));
setRight(getLeft());
setBottom(getTop());
requestLayout();
}
}
super.setText(text, type);
if (doHack)
TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(this, minTextSize, maxTextSize, granularity, TypedValue.COMPLEX_UNIT_PX);
}
...
}
Just .setText("") before resetting the text size you want. That ensures that you are not setting the textsize and then immediately autoresizing using the previous text value in the TextView. Like this:
TextView wordWordTextView = getView().findViewById(R.id.wordWordTextView);
wordWordTextView.setAlpha(0.0f);
wordWordTextView.setText("");
wordWordTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 50);
wordWordTextView.setText(wordStr);
wordWordTextView.animate().alpha(1.0f).setDuration(250);
I only just set android:maxLines="1" in xml file, then code in bindViewHolder
TextViewCompat.setAutoSizeTextTypeWithDefaults(binding.tvResultExplain, TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE);
binding.tvResultExplain.setText("");
TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(binding.tvResultExplain, 12,
16, 1, TypedValue.COMPLEX_UNIT_SP);
binding.tvResultExplain.setText(item.getStatusExplain());
It works for me, maybe it can resolve your situation as well.
Background
Android has a standard ProgressBar with a special animation when being indeterminate . There are also plenty of libraries of so many kinds of progress views that are available (here).
The problem
In all that I've searched, I can't find a way to do a very simple thing:
Have a gradient from color X to color Y, that shows horizontally, and moves in X coordinate so that the colors before X will go to color Y.
For example (just an illustration) , if I have a gradient of blue<->red , from edge to edge , it would go as such:
What I've tried
I've tried some solutions offered here on StackOverflow:
Change horizontal progress bar indeterminate color
How to change android indeterminate ProgressBar color?
Custom Drawable for ProgressBar/ProgressDialog
How to change progress bar's progress color in Android
How to Change Horizontal ProgressBar start color and end Color gradient
but sadly they all are about the standard ProgressBar view of Android, which means it has a different way of showing the animation of the drawable.
I've also tried finding something similar on Android Arsenal website, but even though there are many nice ones, I couldn't find such a thing.
Of course, I could just animate 2 views myself, each has a gradient of its own (one opposite of the other), but I'm sure there is a better way.
The question
Is is possible to use a Drawable or an animation of it, that makes a gradient (or anything else) move this way (repeating of course)?
Maybe just extend from ImageView and animate the drawable there?
Is it also possible to set how much of the container will be used for the repeating drawable ? I mean, in the above example, it could be from blue to red, so that the blue will be on the edges, and the red color would be in the middle .
EDIT:
OK, I've made a bit of a progress, but I'm not sure if the movement is ok, and I think that it won't be consistent in speed as it should, in case the CPU is a bit busy, because it doesn't consider frame drops. What I did is to draw 2 GradientDrawables one next to another, as such:
class HorizontalProgressView #JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val speedInPercentage = 1.5f
private var xMovement: Float = 0.0f
private val rightDrawable: GradientDrawable = GradientDrawable()
private val leftDrawable: GradientDrawable = GradientDrawable()
init {
if (isInEditMode)
setGradientColors(intArrayOf(Color.RED, Color.BLUE))
rightDrawable.gradientType = GradientDrawable.LINEAR_GRADIENT;
rightDrawable.orientation = GradientDrawable.Orientation.LEFT_RIGHT
rightDrawable.shape = GradientDrawable.RECTANGLE;
leftDrawable.gradientType = GradientDrawable.LINEAR_GRADIENT;
leftDrawable.orientation = GradientDrawable.Orientation.RIGHT_LEFT
leftDrawable.shape = GradientDrawable.RECTANGLE;
}
fun setGradientColors(colors: IntArray) {
rightDrawable.colors = colors
leftDrawable.colors = colors
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val widthSize = View.MeasureSpec.getSize(widthMeasureSpec)
val heightSize = View.MeasureSpec.getSize(heightMeasureSpec)
rightDrawable.setBounds(0, 0, widthSize, heightSize)
leftDrawable.setBounds(0, 0, widthSize, heightSize)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.save()
if (xMovement < width) {
canvas.translate(xMovement, 0.0f)
rightDrawable.draw(canvas)
canvas.translate(-width.toFloat(), 0.0f)
leftDrawable.draw(canvas)
} else {
//now the left one is actually on the right
canvas.translate(xMovement - width, 0.0f)
leftDrawable.draw(canvas)
canvas.translate(-width.toFloat(), 0.0f)
rightDrawable.draw(canvas)
}
canvas.restore()
xMovement += speedInPercentage * width / 100.0f
if (isInEditMode)
return
if (xMovement >= width * 2.0f)
xMovement = 0.0f
invalidate()
}
}
usage:
horizontalProgressView.setGradientColors(intArrayOf(Color.RED, Color.BLUE))
And the result (it does loop well, just hard to edit the video) :
So my question now is, what should I do to make sure it animates well, even if the UI thread is a bit busy ?
It's just that the invalidate doesn't seem a reliable way to me to do it, alone. I think it should check more than that. Maybe it could use some animation API instead, with interpolator .
I've decided to put " pskink" answer here in Kotlin (origin here). I write it here only because the other solutions either didn't work, or were workarounds instead of what I asked about.
class ScrollingGradient(private val pixelsPerSecond: Float) : Drawable(), Animatable, TimeAnimator.TimeListener {
private val paint = Paint()
private var x: Float = 0.toFloat()
private val animator = TimeAnimator()
init {
animator.setTimeListener(this)
}
override fun onBoundsChange(bounds: Rect) {
paint.shader = LinearGradient(0f, 0f, bounds.width().toFloat(), 0f, Color.WHITE, Color.BLUE, Shader.TileMode.MIRROR)
}
override fun draw(canvas: Canvas) {
canvas.clipRect(bounds)
canvas.translate(x, 0f)
canvas.drawPaint(paint)
}
override fun setAlpha(alpha: Int) {}
override fun setColorFilter(colorFilter: ColorFilter?) {}
override fun getOpacity(): Int = PixelFormat.TRANSLUCENT
override fun start() {
animator.start()
}
override fun stop() {
animator.cancel()
}
override fun isRunning(): Boolean = animator.isRunning
override fun onTimeUpdate(animation: TimeAnimator, totalTime: Long, deltaTime: Long) {
x = pixelsPerSecond * totalTime / 1000
invalidateSelf()
}
}
usage:
MainActivity.kt
val px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200f, resources.getDisplayMetrics())
progress.indeterminateDrawable = ScrollingGradient(px)
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"
tools:context=".MainActivity">
<ProgressBar
android:id="#+id/progress" style="?android:attr/progressBarStyleHorizontal" android:layout_width="200dp"
android:layout_height="20dp" android:indeterminate="true"/>
</LinearLayout>
The idea behind my solution is relatively simple: display a FrameLayout that has two child views (a start-end gradient and a end-start gradient) and use a ValueAnimator to animate the child views' translationX attribute. Because you're not doing any custom drawing, and because you're using the framework-provided animation utilities, you shouldn't have to worry about animation performance.
I created a custom FrameLayout subclass to manage all this for you. All you have to do is add an instance of the view to your layout, like this:
<com.example.MyHorizontalProgress
android:layout_width="match_parent"
android:layout_height="6dp"
app:animationDuration="2000"
app:gradientStartColor="#000"
app:gradientEndColor="#fff"/>
You can customize the gradient colors and the speed of the animation directly from XML.
The code
First we need to define our custom attributes in res/values/attrs.xml:
<declare-styleable name="MyHorizontalProgress">
<attr name="animationDuration" format="integer"/>
<attr name="gradientStartColor" format="color"/>
<attr name="gradientEndColor" format="color"/>
</declare-styleable>
And we have a layout resource file to inflate our two animated views:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<View
android:id="#+id/one"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<View
android:id="#+id/two"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</merge>
And here's the Java:
public class MyHorizontalProgress extends FrameLayout {
private static final int DEFAULT_ANIMATION_DURATION = 2000;
private static final int DEFAULT_START_COLOR = Color.RED;
private static final int DEFAULT_END_COLOR = Color.BLUE;
private final View one;
private final View two;
private int animationDuration;
private int startColor;
private int endColor;
private int laidOutWidth;
public MyHorizontalProgress(Context context, AttributeSet attrs) {
super(context, attrs);
inflate(context, R.layout.my_horizontal_progress, this);
readAttributes(attrs);
one = findViewById(R.id.one);
two = findViewById(R.id.two);
ViewCompat.setBackground(one, new GradientDrawable(LEFT_RIGHT, new int[]{ startColor, endColor }));
ViewCompat.setBackground(two, new GradientDrawable(LEFT_RIGHT, new int[]{ endColor, startColor }));
getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
laidOutWidth = MyHorizontalProgress.this.getWidth();
ValueAnimator animator = ValueAnimator.ofInt(0, 2 * laidOutWidth);
animator.setInterpolator(new LinearInterpolator());
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.setRepeatMode(ValueAnimator.RESTART);
animator.setDuration(animationDuration);
animator.addUpdateListener(updateListener);
animator.start();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
else {
getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
}
private void readAttributes(AttributeSet attrs) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.MyHorizontalProgress);
animationDuration = a.getInt(R.styleable.MyHorizontalProgress_animationDuration, DEFAULT_ANIMATION_DURATION);
startColor = a.getColor(R.styleable.MyHorizontalProgress_gradientStartColor, DEFAULT_START_COLOR);
endColor = a.getColor(R.styleable.MyHorizontalProgress_gradientEndColor, DEFAULT_END_COLOR);
a.recycle();
}
private ValueAnimator.AnimatorUpdateListener updateListener = new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
int offset = (int) valueAnimator.getAnimatedValue();
one.setTranslationX(calculateOneTranslationX(laidOutWidth, offset));
two.setTranslationX(calculateTwoTranslationX(laidOutWidth, offset));
}
};
private int calculateOneTranslationX(int width, int offset) {
return (-1 * width) + offset;
}
private int calculateTwoTranslationX(int width, int offset) {
if (offset <= width) {
return offset;
}
else {
return (-2 * width) + offset;
}
}
}
How the Java works is pretty simple. Here's a step-by-step of what's going on:
Inflate our layout resource, adding our two to-be-animated children into the FrameLayout
Read the animation duration and color values from the AttributeSet
Find the one and two child views (not very creative names, I know)
Create a GradientDrawable for each child view and apply it as the background
Use an OnGlobalLayoutListener to set up our animation
The use of the OnGlobalLayoutListener makes sure we get a real value for the width of the progress bar, and makes sure we don't start animating until we're laid out.
The animation is pretty simple as well. We set up an infinitely-repeating ValueAnimator that emits values between 0 and 2 * width. On each "update" event, our updateListener calls setTranslationX() on our child views with a value computed from the emitted "update" value.
And that's it! Let me know if any of the above was unclear and I'll be happy to help.
final View bar = view.findViewById(R.id.progress);
final GradientDrawable background = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, new int[]{Color.BLUE, Color.RED, Color.BLUE, Color.RED});
bar.setBackground(background);
bar.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
#Override
public void onLayoutChange(final View v, final int left, final int top, final int right, final int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
background.setBounds(-2 * v.getWidth(), 0, v.getWidth(), v.getHeight());
ValueAnimator animation = ValueAnimator.ofInt(0, 2 * v.getWidth());
animation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
background.setBounds(-2 * v.getWidth() + (int) animation.getAnimatedValue(), 0, v.getWidth() + (int) animation.getAnimatedValue(), v.getHeight());
}
});
animation.setRepeatMode(ValueAnimator.RESTART);
animation.setInterpolator(new LinearInterpolator());
animation.setRepeatCount(ValueAnimator.INFINITE);
animation.setDuration(3000);
animation.start();
}
});
This is the view for testing:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center" >
<View
android:id="#+id/progress"
android:layout_width="match_parent"
android:layout_height="40dp"/>
</FrameLayout>
I've modified 'android developer's code slightly which might help some people.
The animation didn't seem to resize properly so I've fixed that, made the animation speed a bit easier to set (seconds instead of pixel based) and relocated the init code to allow embedding right into the layout xml without code in your Activity.
ScrollingProgressBar.kt
package com.test
import android.content.Context
import android.util.AttributeSet
import android.widget.ProgressBar
import android.animation.TimeAnimator
import android.graphics.*
import android.graphics.drawable.Animatable
import android.graphics.drawable.Drawable
class ScrollingGradient : Drawable(), Animatable, TimeAnimator.TimeListener {
private val paint = Paint()
private var x: Float = 0.toFloat()
private val animator = TimeAnimator()
private var pixelsPerSecond: Float = 0f
private val animationTime: Int = 2
init {
animator.setTimeListener(this)
}
override fun onBoundsChange(bounds: Rect) {
paint.shader = LinearGradient(0f, 0f, bounds.width().toFloat(), 0f, Color.parseColor("#00D3D3D3"), Color.parseColor("#CCD3D3D3"), Shader.TileMode.MIRROR)
pixelsPerSecond = ((bounds.right - bounds.left) / animationTime).toFloat()
}
override fun draw(canvas: Canvas) {
canvas.clipRect(bounds)
canvas.translate(x, 0f)
canvas.drawPaint(paint)
}
override fun setAlpha(alpha: Int) {}
override fun setColorFilter(colorFilter: ColorFilter?) {}
override fun getOpacity(): Int = PixelFormat.TRANSLUCENT
override fun start() {
animator.start()
}
override fun stop() {
animator.cancel()
}
override fun isRunning(): Boolean = animator.isRunning
override fun onTimeUpdate(animation: TimeAnimator, totalTime: Long, deltaTime: Long) {
x = pixelsPerSecond * totalTime / 1000
invalidateSelf()
}
}
class ScrollingProgressBar : ProgressBar {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
init {
this.indeterminateDrawable = ScrollingGradient()
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
this.indeterminateDrawable.setBounds(this.left, this.top, this.right, this.bottom)
}
}
Layout xml (replace com.test.ScrollingProgressBar with the location of code above)
<com.test.ScrollingProgressBar
android:id="#+id/progressBar1"
android:background="#464646"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="80dp"
android:gravity="center"
android:indeterminateOnly="true"/>
You may achieve it if you have different drawables which defines the colors which are required to show as progress bar.
Use AnimationDrawable animation_list
<animation-list android:id="#+id/selected" android:oneshot="false">
<item android:drawable="#drawable/color1" android:duration="50" />
<item android:drawable="#drawable/color2" android:duration="50" />
<item android:drawable="#drawable/color3" android:duration="50" />
<item android:drawable="#drawable/color4" android:duration="50" />
-----
-----
</animation-list>
And in your Activity/xml set this as a background resource to your progressbar.
Then do as follows
// Get the background, which has been compiled to an AnimationDrawable object.
AnimationDrawable frameAnimation = (AnimationDrawable)prgressBar.getBackground();
// Start the animation (looped playback by default).
frameAnimation.start();
If we take the respective drawables in such a way which covers blue to red
and red to blue gradient effects respectively those images we have to mention in animation list as color1, color2 etc
This approach is similar to how we will make a GIF image with multiple static images.
for performance I would extend the ProgressBar class and override the onDraw method myself. Then draw a Rect with the proper Gradient in the Paint :
Canvas's drawRect method where you specify coordinates and the Paint
Here is a good android input to start custom drawing :
Custom drawing by Android
And here is a simple start example of a custom drawing view :
Simple example using onDraw
So, in code, something like this would do for a static Gradient :
public class MyView extends View {
private int color1 = 0, color2 = 1;
private LinearGradient linearGradient = new LinearGradient(0,0,0,0,color1,color2, Shader.TileMode.REPEAT);
Paint p;
public MyView(Context context) {
super(context);
}
#Override
protected synchronized void onDraw(Canvas canvas) {
p = new Paint();
p.setDither(true);
p.setShader(linearGradient);
canvas.drawRect(0,0,getWidth(),getHeight(),p);
}
#Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
linearGradient = new LinearGradient(0,heightMeasureSpec/2, widthMeasureSpec,heightMeasureSpec/2,color1,color2, Shader.TileMode.REPEAT);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
You can play with LinearGradient other constructor to get the desired effect (accepts a list of points, you would probably need 3 of them, the one in the middle giving the progress). You can implement the progress with a variable in your view. The onMeasure method allows me to adapt to the view changing it's size. You can create a setProgress(float progress) method that sets a variable progress and invalidates the View :
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.view.View;
public class MyProgressBar extends View {
private int myWidth = 0, myHeight = 0;
private int[] myColors = new int[]{0,1};
private float[] myPositions = new float[]{0.0f,0.0f,1.0f};
private LinearGradient myLinearGradient = new LinearGradient(0,0,myWidth,myHeight/2,myColors,myPositions, Shader.TileMode.REPEAT);
private Paint myPaint = new Paint();
public MyProgressBar(Context context) {
super(context);
myPaint.setDither(true);
}
#Override
protected synchronized void onDraw(Canvas canvas) {
myPaint.setShader(myLinearGradient);
canvas.drawRect(0,0,getWidth(),getHeight(),p);
}
#Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
myWidth = widthMeasureSpec;
myHeight = heightMeasureSpec;
myLinearGradient = new LinearGradient(0,0,myWidth,myHeight/2,myColors,myPositions, Shader.TileMode.REPEAT);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
// progress must be a percentage, a float between 0.0f and 1.0f
public void setProgress(float progress) {
myPositions[1] = progress;
myLinearGradient = new LinearGradient(0,0,myWidth,myHeight/2,myColors,myPositions, Shader.TileMode.REPEAT);
this.invalidate();
}
}
Of course, you have to use the setProgress(progress) method for it to be dynamic.
I'm writing a calendar application for Android. The calendar needs to a have a day display similar to the default application, or MS outlook: a grid showing a line for each hour, and the appointments shown as rectangles.
Here's a similar sample image from Google Images:
I downloaded the source code for the calendar app from Google's Android Open Source Project, and saw that they implemented this display as a custom view which simplay uses Canvas.drawRect() to draw the rectangles, and then they implemented their own hit-test when the user clicks, to see which appointment was clicked.
I already wrote some of that stuff on my own and it works great, and isn't too complicated.
The problem is that I need the different lines of text inside the rectangles (the subject, the time) to be links to various functionality, and I'm wondering how I can do that.
When I draw, I already create Rects for each appointment. I was thinking I could create Rects for each piece of text as well, cache all of these in an ArrayList, and then perform the histtest against the cached rects. I'm only afraid this whole thing will be too heavy... does this sound like a solid design?
Or should I avoid the custom drawing altogether and programmatically generate and place views (TextViews maybe?) I'm an Android novice and I'm not sure what my options are...
Thanks for helping out!
Alright, as announced, here some example:
If you just use a custom view, you have to keep lists of objects and draw them yourself, as opposed to a custom layout where you just have to measure and layout the children. Since you can just add a button, there's no need to use hit-tests or whatsoever, since if you don't mess up the view will just receive the onClick() call.
Also, you can easily preview your layout in the editor if you correctly implement layout parameters. Which makes development much faster.
E.g. you can define your own layout parameters
<resources>
<declare-styleable name="TimeLineLayout_Layout">
<attr name="time_from" format="string"/>
<attr name="time_to" format="string"/>
</declare-styleable>
</resources>
Then use them like this...
<com.github.bleeding182.timelinelayout.TimeLineLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#22662222">
<TextView
android:layout_width="80dp"
android:layout_height="wrap_content"
android:background="#android:color/holo_green_dark"
android:padding="8dp"
android:text="12:00 - 16:00"
app:time_from="12:00"
app:time_to="16:00"/>
</com.github.bleeding182.timelinelayout.TimeLineLayout>
And the result would look something like this (I know it's ugly, but I made this just for testing :/ )
To do this, you create a basic layout where you measure and layout the views. You can then add any views to your layout, and by setting a time from / to and correctly measuring / layouting you can easily display all sorts of items.
The code for the screenshot is attached below, onDraw will create those ugly hour/half hour lines. onMeasure is for calculating view heights and onLayout is drawing the views to their correct time slot.
I hope this helps, it's sure easier to use than handling everything in one view.
public class TimeLineLayout extends ViewGroup {
private int tIntervalSpan = 24 * 60;
private float mMeasuredMinuteHeight;
public TimeLineLayout(Context context) {
super(context);
}
public TimeLineLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TimeLineLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public TimeLineLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
for (int i = 0; i < getChildCount(); i++) {
final View child = getChildAt(i);
ViewGroup.LayoutParams layoutParams = child.getLayoutParams();
if (layoutParams instanceof LayoutParams) {
LayoutParams params = (LayoutParams) layoutParams;
final int top = (int) (params.tFrom * mMeasuredMinuteHeight);
child.layout(l, top, child.getMeasuredWidth(), top + child.getMeasuredHeight());
}
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
mMeasuredMinuteHeight = getMeasuredHeight() / (float) tIntervalSpan;
for (int i = 0; i < getChildCount(); i++) {
final View child = getChildAt(i);
ViewGroup.LayoutParams layoutParams = child.getLayoutParams();
if (layoutParams instanceof LayoutParams) {
LayoutParams params = (LayoutParams) layoutParams;
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec((int) ((params.tTo - params.tFrom) * mMeasuredMinuteHeight), MeasureSpec.EXACTLY));
}
}
}
#Override
protected void onDraw(Canvas canvas) {
final float height = mMeasuredMinuteHeight * 60;
Paint paint = new Paint();
paint.setColor(Color.RED);
for(int i = 0; i < 24; i++) {
paint.setStrokeWidth(2f);
paint.setAlpha(255);
canvas.drawLine(0, i * height, getMeasuredWidth(), i*height, paint);
if(i < 23) {
paint.setStrokeWidth(1f);
paint.setAlpha(50);
canvas.drawLine(0, i * height + 30 * mMeasuredMinuteHeight, getMeasuredWidth(), i * height + 30 * mMeasuredMinuteHeight, paint);
}
}
}
#Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams;
}
#Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
public static class LayoutParams extends ViewGroup.LayoutParams {
private final int tFrom;
private final int tTo;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.TimeLineLayout_Layout);
final String from = a.getString(R.styleable.TimeLineLayout_Layout_time_from);
final String to = a.getString(R.styleable.TimeLineLayout_Layout_time_to);
a.recycle();
tFrom = Integer.parseInt(from.split(":")[0]) * 60 + Integer.parseInt(from.split(":")[1]);
tTo = Integer.parseInt(to.split(":")[0]) * 60 + Integer.parseInt(to.split(":")[1]);
}
}
I am trying to reduce the line spacing in a TextView by setting a negative 'add' to TextView.setLineSpacing(). It works well except that the bottom line get truncated.
Main layout
<TextView
android:id="#+id/text_view"
android:padding="dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
tools:context=".MainActivity" />
Main activity: (notice the
package com.font_test;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/custom_fonts.ttf");
final TextView tv = (TextView) findViewById(R.id.text_view);
tv.setTypeface(typeface);
tv.setTextSize(60);
tv.setLineSpacing(-30f, 1f); // *** -30 to reduce line spacing
tv.setBackgroundColor(0x280000ff);
tv.setText("gggkiiikkk" + "\n" + "gikgikgik" + "\n" + "kigkigkig");
}
}
This results in truncation at the bottom of the view (notice the 'g' at the bottom line):
It seems that the problem is related to incorrect layout measurement. If I set the TextView to
android:layout_height="fill_parent"
It does render properly:
Any idea how to fix it? I don't mind to have ugly workarounds if it helps. I also have access to FontForge and I can modify the font file if needed.
littleFluffyKittys answer is good but it didn't work on some devices if the linespacing was set through xml
I calculate the additional height needed by comparing the original height of the font with the height the textview calculates for a line.
If the line height is smaller than the height of the font the diffrence is added one time.
This works down to at least API 10 propably lower (just not tested any lower)
public class ReducedLineSpacingTextView extends TextView {
public ReducedLineSpacingTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ReducedLineSpacingTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ReducedLineSpacingTextView(Context context) {
super(context);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int truncatedHeight = getPaint().getFontMetricsInt(null) - getLineHeight();
if (truncatedHeight > 0) {
setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight() + truncatedHeight);
}
}
}
I ran into this same problem but when I was trying to use a spacing multiplier less than 1.
I created a subclass of TextView that fixes the truncation of the last line automatically and doesn't require you set a known/fixed spacing at the bottom.
Just use this class and you can use it normally, you don't need to apply any additional spacing or fixes.
public class ReducedLineSpacingTextView extends TextView {
private boolean mNegativeLineSpacing = false;
public ReducedLineSpacingTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ReducedLineSpacingTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ReducedLineSpacingTextView(Context context) {
super(context);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mNegativeLineSpacing) { // If you are only supporting Api Level 16 and up, you could use the getLineSpacingExtra() and getLineSpacingMultiplier() methods here to check for a less than 1 spacing instead.
Layout layout = getLayout();
int truncatedHeight = layout.getLineDescent(layout.getLineCount()-1);
setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight() + truncatedHeight);
}
}
#Override
public void setLineSpacing(float add, float mult) {
mNegativeLineSpacing = add < 0 || mult < 1;
super.setLineSpacing(add, mult);
}
}
Nice!
That'll make the job but it's never a good idea to put constants values wherever we have variables. You can use the lineSpacing values to add them to the onMeasure method in a dinamyc way.
Note that this values are always available through "getLineSpacingExtra()" and "getLineSpacingMultiplier()". Or even easier you can get the value of both summed up: "getLineHeight()".
Although it feels for me that this value should be included in the onMeasure method, you can always measure the exact height you need and then make a simple check:
final int measuredHeight = getMeasuredHeight();
if (measuredHeight < neededHeight) {
setMeasuredDimension(getMeasuredWidth, neededHeight);
}
One last thing, you don't need to pass the context along in a separated attribute. If you have a look to your constructors, the context is already there. If you needed along the code of your component you can just use "getContext()".
Hope it helps.
Use this to reduce line spacing in text view
**
android:lineSpacingMultiplier="0.8"
**
If padding doesn't work, margin should do the job. If you still have problem you can always apply the line spacing value to the onMeasure method of the view. You'll have to create a custom component for that and extend onMeasure.
Just add paddingBottom to declaration of your TextView xml, pick a value which produces a good result. And consequently set values for other paddings (top, let and right). This should fix your problem
This is what I did based on Jose's answer here and it seems to work. I am not very familiar with the intricate of the layout mechanism. Is this code safe? Any problem with it?
Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.font_test.MyTextView
android:id="#+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
tools:context=".MainActivity" />
</RelativeLayout>
Added custom TextView that extends the vertical height by N pixels:
package com.font_test;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// TODO: provide an API to set extra bottom pixels (50 in this example)
setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight() + 50);
}
}
Result text view rendering without truncation at the bottom:
How can I make the textview wrap such text exactly ?
android:width attribute is not a solution, because the text is dynamic.
Desired behaviour
|Adcs |
|adscfd|
Current behavour:
|Adcs |
|adscfd |
Hereis the code (styles of TextViews only define things like textColor, textSize, textStyle).
<TextView
android:id="#+id/text_title_holder"
style="#style/TextBold.Black.Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:maxWidth="100dp"
android:maxLines="2"
android:text="Adcs adscfd"
android:gravity="left"
android:visibility="visible" />
The topic wrap_content width on mutiline TextView has no good answer.
I have faced this problem and didn't find the solution in internet. I did this trick by creating the new component TightTextView that remeasures the given text in case you have specified the maxWidth of the component and the width of Layout (of text) is less that the measured width of the view.
package com.client.android.app.views;
import android.content.Context;
import android.text.Layout;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Tightly wraps the text when setting the maxWidth.
* #author sky
*/
public class TightTextView extends TextView {
private boolean hasMaxWidth;
public TightTextView(Context context) {
this(context, null, 0);
}
public TightTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TightTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (hasMaxWidth) {
int specModeW = MeasureSpec.getMode(widthMeasureSpec);
if (specModeW != MeasureSpec.EXACTLY) {
Layout layout = getLayout();
int linesCount = layout.getLineCount();
if (linesCount > 1) {
float textRealMaxWidth = 0;
for (int n = 0; n < linesCount; ++n) {
textRealMaxWidth = Math.max(textRealMaxWidth, layout.getLineWidth(n));
}
int w = Math.round(textRealMaxWidth);
if (w < getMeasuredWidth()) {
super.onMeasure(MeasureSpec.makeMeasureSpec(w, MeasureSpec.AT_MOST),
heightMeasureSpec);
}
}
}
}
}
#Override
public void setMaxWidth(int maxpixels) {
super.setMaxWidth(maxpixels);
hasMaxWidth = true;
}
#Override
public void setMaxEms(int maxems) {
super.setMaxEms(maxems);
hasMaxWidth = true;
}
}
!!! Just did port it to older android APIs, cuz getMaxWidth() is only available since API level 16.
This question is a little old now but I too had this problem where I wanted green text in a black box over a mapView and got around it by putting my textView in a RelativeLayout container. I then used padding to set the border size. The textView now hugs the text nicely.
My outline in eclipse looks like this.
RelativeLayout
mapview
LinearLayout
RelativeLayout
textView1 << this is the box I want to hug the text
imageView1
RelativeLayout
etc....
Hope this helps.