Vertical (Rotated) Label in Android

Vertical (rotated) label in Android

Here is my elegant and simple vertical text implementation, extending TextView. This means that all standard styles of TextView may be used, because it is extended TextView.

public class VerticalTextView extends TextView{
final boolean topDown;

public VerticalTextView(Context context, AttributeSet attrs){
super(context, attrs);
final int gravity = getGravity();
if(Gravity.isVertical(gravity) && (gravity&Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
setGravity((gravity&Gravity.HORIZONTAL_GRAVITY_MASK) | Gravity.TOP);
topDown = false;
}else
topDown = true;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(heightMeasureSpec, widthMeasureSpec);
setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
}

@Override
protected boolean setFrame(int l, int t, int r, int b){
return super.setFrame(l, t, l+(b-t), t+(r-l));
}

@Override
public void draw(Canvas canvas){
if(topDown){
canvas.translate(getHeight(), 0);
canvas.rotate(90);
}else {
canvas.translate(0, getWidth());
canvas.rotate(-90);
}
canvas.clipRect(0, 0, getWidth(), getHeight(), android.graphics.Region.Op.REPLACE);
super.draw(canvas);
}
}

By default, rotated text is from top to bottom. If you set android:gravity="bottom", then it's drawn from bottom to top.

Technically, it fools underlying TextView to think that it's normal rotation (swapping width/height in few places), while drawing it rotated.
It works fine also when used in an xml layout.

EDIT:
posting another version, above has problems with animations. This new version works better, but loses some TextView features, such as marquee and similar specialties.

public class VerticalTextView extends TextView{
final boolean topDown;

public VerticalTextView(Context context, AttributeSet attrs){
super(context, attrs);
final int gravity = getGravity();
if(Gravity.isVertical(gravity) && (gravity&Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
setGravity((gravity&Gravity.HORIZONTAL_GRAVITY_MASK) | Gravity.TOP);
topDown = false;
}else
topDown = true;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(heightMeasureSpec, widthMeasureSpec);
setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
}

@Override
protected void onDraw(Canvas canvas){
TextPaint textPaint = getPaint();
textPaint.setColor(getCurrentTextColor());
textPaint.drawableState = getDrawableState();

canvas.save();

if(topDown){
canvas.translate(getWidth(), 0);
canvas.rotate(90);
}else {
canvas.translate(0, getHeight());
canvas.rotate(-90);
}


canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop());

getLayout().draw(canvas);
canvas.restore();
}
}

EDIT
Kotlin version:

import android.content.Context
import android.graphics.Canvas
import android.text.BoringLayout
import android.text.Layout
import android.text.TextUtils.TruncateAt
import android.util.AttributeSet
import android.view.Gravity
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.graphics.withSave

class VerticalTextView(context: Context, attrs: AttributeSet) : AppCompatTextView(context, attrs) {
private val topDown = gravity.let { g ->
!(Gravity.isVertical(g) && g.and(Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM)
}
private val metrics = BoringLayout.Metrics()
private var padLeft = 0
private var padTop = 0

private var layout1: Layout? = null

override fun setText(text: CharSequence, type: BufferType) {
super.setText(text, type)
layout1 = null
}

private fun makeLayout(): Layout {
if (layout1 == null) {
metrics.width = height
paint.color = currentTextColor
paint.drawableState = drawableState
layout1 = BoringLayout.make(text, paint, metrics.width, Layout.Alignment.ALIGN_NORMAL, 2f, 0f, metrics, false, TruncateAt.END, height - compoundPaddingLeft - compoundPaddingRight)
padLeft = compoundPaddingLeft
padTop = extendedPaddingTop
}
return layout1!!
}

override fun onDraw(c: Canvas) {
// c.drawColor(0xffffff80); // TEST
if (layout == null)
return
c.withSave {
if (topDown) {
val fm = paint.fontMetrics
translate(textSize - (fm.bottom + fm.descent), 0f)
rotate(90f)
} else {
translate(textSize, height.toFloat())
rotate(-90f)
}
translate(padLeft.toFloat(), padTop.toFloat())
makeLayout().draw(this)
}
}
}

Rotate value text vertically outside bar in BarChart MPAndroidChart

I was able to fix it by moving the label up.

Worth noticing is x and y dimensions changes internally as we are rotating the label so for moving label up you have to increase x value and not y value.

Also note to make it dynamic and work for all text lengths, I am calculating the pixel size for text to be displayed and moving label up by that pixel size only. See code below (in kotlin):

override fun drawValue(c: Canvas, formatter: IValueFormatter, value: Float, entry: Entry, dataSetIndex: Int, x: Float, y: Float, color: Int) {
mValuePaint.color = Color.WHITE
val text = formatter.getFormattedValue(value, entry, dataSetIndex, mViewPortHandler)

c.save()
val width = mValuePaint.measureText(text)
c.rotate(-90f, x, y)

c.drawText(text, x + (width / 2), y, mValuePaint)
c.restore()
}

android text view text in vertical direction

You could extend TextView to your custom VerticalTextView and override setText() method. In setText implementation you could iterate through text and modify it inserting linebreaks \n. After you finish just set result value to your view.

Rotated text in AppWidget

If it weren’t a specific AppWidget case I would recommend you to use custom view such as this answer suggests.

It is Widget though, thus we cannot use custom views. We can use dirty hacks though.

Try this hack:

  • Hard-code the layout_width and layout_heightof the TextView larger than the expected text size - for example 1024dp x 1024dp.

  • Place your TextView in a FrameLayout

  • Use a gravity attribute to position the text within TextView boundary.

  • Use a layout_gravity attribute to position the TextView inside FrameLayout

In your case it will look something like this:

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">

<FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="8dp">
<TextView
android:layout_width="1024dp"
android:layout_height="1024dp"
android:layout_gravity="center"
android:gravity="center"
android:rotation="-90"
android:text="Some text smaller than container" />
</FrameLayout>
<FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="8dp">
<TextView
android:layout_width="1024dp"
android:layout_height="1024dp"
android:layout_gravity="center"
android:gravity="center"
android:rotation="-90"
android:text="Some text smaller than container" />
</FrameLayout>
<FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="8dp">
<TextView
android:layout_width="1024dp"
android:layout_height="1024dp"
android:layout_gravity="center"
android:gravity="center"
android:rotation="-90"
android:text="Some text smaller than container" />
</FrameLayout>

</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">

<FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="8dp">
<TextView
android:layout_width="1024dp"
android:layout_height="1024dp"
android:layout_gravity="center"
android:gravity="center"
android:rotation="-90"
android:text="Some text smaller than container" />
</FrameLayout>
<FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="8dp">
<TextView
android:layout_width="1024dp"
android:layout_height="1024dp"
android:layout_gravity="center"
android:gravity="center"
android:rotation="-90"
android:text="Some text smaller than container" />
</FrameLayout>
<FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="8dp">
<TextView
android:layout_width="1024dp"
android:layout_height="1024dp"
android:layout_gravity="center"
android:gravity="center"
android:rotation="-90"
android:text="Some text smaller than container" />
</FrameLayout>

</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">

<FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="8dp">
<TextView
android:layout_width="1024dp"
android:layout_height="1024dp"
android:layout_gravity="center"
android:gravity="center"
android:rotation="-90"
android:text="Some text smaller than container" />
</FrameLayout>
<FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="8dp">
<TextView
android:layout_width="1024dp"
android:layout_height="1024dp"
android:layout_gravity="center"
android:gravity="center"
android:rotation="-90"
android:text="Some text smaller than container" />
</FrameLayout>
<FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:padding="8dp">
<TextView
android:layout_width="1024dp"
android:layout_height="1024dp"
android:layout_gravity="center"
android:gravity="center"
android:rotation="-90"
android:text="Some text smaller than container" />
</FrameLayout>

</LinearLayout>

</LinearLayout>

Android ActionBar menu with vertical (rotated) text items based on Custom Action Provider

If You didn't find Custom Action Provider based solution, may be You want use Custom Toolbar & PopupWindow-based workaround which means:

1) create custom Toolbar with ImageButton as menu button and replace ActionBar with it (like in that post of Machado);

2) create PopupWindow with custom layout for menu items with vertical text;

3) add onClickListener to ImageButton from p.1 which show PopupWindow from p.2.

Layout of custom Toolbar (action_bar.xml) may be something like:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="fill_horizontal"
android:orientation="vertical">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:background="@color/colorPrimary"
android:elevation="4dp"
android:layout_height="?attr/actionBarSize">
</android.support.v7.widget.Toolbar>
</RelativeLayout>

Layout of MainActivity (activity_main.xml) which use it:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/activity_main"
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"
android:padding="0dp"
tools:context="<your_package_name>.MainActivity">

<include
android:id="@+id/tool_bar"
layout="@layout/action_bar"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_marginStart="31dp"
android:layout_below="@+id/tool_bar"
android:layout_alignParentStart="true"
android:layout_marginTop="31dp"/>

</RelativeLayout>

ImageButton as "main popup menu" button described in main_menu.xml file this way (more in this post of ASH):

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/menu_button"
android:icon="@drawable/ic_more_vert"
android:title=""
app:showAsAction="always"
app:actionViewClass="android.widget.ImageButton"/>
</menu>

For vertical text of menu items You can use, for example, custom View like VerticalLabelView from this of kostmo:

public class VerticalLabelView extends View {
private TextPaint mTextPaint;
private String mText;
private int mAscent;
private Rect text_bounds = new Rect();

final static int DEFAULT_TEXT_SIZE = 15;

public VerticalLabelView(Context context) {
super(context);
initLabelView();
}

public VerticalLabelView(Context context, AttributeSet attrs) {
super(context, attrs);
initLabelView();

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.VerticalLabelView);

CharSequence s = a.getString(R.styleable.VerticalLabelView_text);
if (s != null) setText(s.toString());

setTextColor(a.getColor(R.styleable.VerticalLabelView_textColor, 0xFF000000));

int textSize = a.getDimensionPixelOffset(R.styleable.VerticalLabelView_textSize, 0);
if (textSize > 0) setTextSize(textSize);

a.recycle();
}

private final void initLabelView() {
mTextPaint = new TextPaint();
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(DEFAULT_TEXT_SIZE);
mTextPaint.setColor(0xFF000000);
mTextPaint.setTextAlign(Align.CENTER);
setPadding(3, 3, 3, 3);
}

public void setText(String text) {
mText = text;
requestLayout();
invalidate();
}

public void setTextSize(int size) {
mTextPaint.setTextSize(size);
requestLayout();
invalidate();
}

public void setTextColor(int color) {
mTextPaint.setColor(color);
invalidate();
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

mTextPaint.getTextBounds(mText, 0, mText.length(), text_bounds);
setMeasuredDimension(
measureWidth(widthMeasureSpec),
measureHeight(heightMeasureSpec));
}

private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);

if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
// Measure the text
result = text_bounds.height() + getPaddingLeft() + getPaddingRight();

if (specMode == MeasureSpec.AT_MOST) {
// Respect AT_MOST value if that was what is called for by measureSpec
result = Math.min(result, specSize);
}
}
return result;
}

private int measureHeight(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);

mAscent = (int) mTextPaint.ascent();
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
// Measure the text
result = text_bounds.width() + getPaddingTop() + getPaddingBottom();

if (specMode == MeasureSpec.AT_MOST) {
// Respect AT_MOST value if that was what is called for by measureSpec
result = Math.min(result, specSize);
}
}
return result;
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);

float text_horizontally_centered_origin_x = getPaddingLeft() + text_bounds.width()/2f;
float text_horizontally_centered_origin_y = getPaddingTop() - mAscent;

canvas.translate(text_horizontally_centered_origin_y, text_horizontally_centered_origin_x);
canvas.rotate(-90);
canvas.drawText(mText, 0, 0, mTextPaint);
}
}

(NB: may be You need to customize paddings of VerticalLabelView: on line
result = text_bounds.height() + getPaddingLeft() + getPaddingRight() + 16;
add "+16" for better padding)

and attrs.xml for VerticalLabelView class:

<resources>
<declare-styleable name="VerticalLabelView">
<attr name="text" format="string" />
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
</declare-styleable>
</resources>

Layout for PopupWindow (menu_layout.xml) in this case might be like:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/menu_root"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="@dimen/activity_horizontal_margin">

<<your_package_name>.VerticalLabelView
android:id="@+id/menu_item1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:textSize="18sp"
android:layout_margin="16dp"
android:padding="4dp"
android:text="Vertical menu item 1"/>

<<your_package_name>.VerticalLabelView
android:id="@+id/menu_item2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:textSize="18sp"
android:layout_margin="16dp"
android:padding="4dp"
android:text="Vertical menu item 2"/>

<<your_package_name>.VerticalLabelView
android:id="@+id/menu_item3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:textSize="18sp"
android:layout_margin="16dp"
android:padding="4dp"
android:text="Vertical menu item 3"/>

<<your_package_name>.VerticalLabelView
android:id="@+id/menu_item4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:textSize="18sp"
android:layout_margin="16dp"
android:padding="4dp"
android:text="Vertical menu item 4"/>

</LinearLayout>

And MainActivity class can be like:

public class MainActivity extends AppCompatActivity {

private static final String TAG = MainActivity.class.getSimpleName();

private Toolbar mToolbar;
private int mToolbarTitleColor;
private ImageButton mMainMenuButton;
private int mActionBarSize;
private PopupWindow mPopupMenu;
private int mTextSize = 48;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
mActionBarSize = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}

mToolbarTitleColor = Color.WHITE;
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setTitleTextColor(mToolbarTitleColor);

setSupportActionBar(mToolbar);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);

Drawable menuIcon = ContextCompat.getDrawable(this, R.drawable.ic_more_vert);
menuIcon.setColorFilter(mToolbarTitleColor, PorterDuff.Mode.SRC_ATOP);

getMenuInflater().inflate(R.menu.main_menu, menu);
mMainMenuButton = (ImageButton) menu.findItem(R.id.menu_button).getActionView();
mMainMenuButton.setBackground(null);
mMainMenuButton.setImageDrawable(menuIcon);
mMainMenuButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mPopupMenu != null && mPopupMenu.isShowing()) {
mPopupMenu.dismiss();
}
mPopupMenu = createPopupMenu();
mPopupMenu.showAtLocation(v, Gravity.TOP | Gravity.RIGHT, 0, mActionBarSize);
}
});
return true;
}

public PopupWindow createPopupMenu() {
final PopupWindow popupWindow = new PopupWindow(this);
LayoutInflater inflater = getLayoutInflater();

View popupView = inflater.inflate(R.layout.menu_layout, null);

VerticalLabelView menuItem1 = (VerticalLabelView)popupView.findViewById(R.id.menu_item1);
menuItem1.setOnClickListener(mOnMenuItemClickListener);
menuItem1.setText("Vertical menu item 1");
menuItem1.setTextColor(Color.WHITE);
menuItem1.setTextSize(mTextSize);

VerticalLabelView menuItem2 = (VerticalLabelView)popupView.findViewById(R.id.menu_item2);
menuItem2.setOnClickListener(mOnMenuItemClickListener);
menuItem2.setText("Vertical menu item 2");
menuItem2.setTextColor(Color.WHITE);
menuItem2.setTextSize(mTextSize);

VerticalLabelView menuItem3 = (VerticalLabelView)popupView.findViewById(R.id.menu_item3);
menuItem3.setOnClickListener(mOnMenuItemClickListener);
menuItem3.setText("Vertical menu item 3");
menuItem3.setTextColor(Color.WHITE);
menuItem3.setTextSize(mTextSize);

VerticalLabelView menuItem4 = (VerticalLabelView)popupView.findViewById(R.id.menu_item4);
menuItem4.setOnClickListener(mOnMenuItemClickListener);
menuItem4.setText("Vertical menu item 4");
menuItem4.setTextColor(Color.WHITE);
menuItem4.setTextSize(mTextSize);

popupWindow.setFocusable(true);
popupWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
popupWindow.setContentView(popupView);

return popupWindow;
}

private View.OnClickListener mOnMenuItemClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.menu_item1: {
Log.d(TAG, "menu_item1");
}
break;
case R.id.menu_item2: {
Log.d(TAG, "menu_item2");
}
break;
case R.id.menu_item3: {
Log.d(TAG, "menu_item3");
}
case R.id.menu_item4: {
Log.d(TAG, "menu_item4");
}
break;
default: {
}
}
if (mPopupMenu != null && mPopupMenu.isShowing()) {
mPopupMenu.dismiss();
}
}
};
}

Ultimatly, as result You should receive something like that:

Vertical menu items screenshot

P.S. Of course You need more elegant solution for createPopupMenu().

How to rotate text of the Button in android?

I found a solution.

I edited the onDraw function. Firstly get width and height of text with getTextBounds()

In getTextBounds() give the the text of your Button as parameter.

And edit the canvas.translate() function like below. And it is centering the text in the button.

@Override
protected void onDraw(Canvas canvas) {
TextPaint textPaint = getPaint();
textPaint.setColor(getCurrentTextColor());
textPaint.drawableState = getDrawableState();
Rect bounds = new Rect();
textPaint.getTextBounds("ENTER",0,"ENTER".length(), bounds);

Log.e("TAG", "onDraw: "+ bounds.width() + " "+bounds.height());
canvas.save();

canvas.translate(getWidth()/2 - bounds.height(), (float) (getHeight()/2 + bounds.width()/1.5));
canvas.rotate(-90);

getLayout().draw(canvas);
canvas.restore();
}

Put rotated text on an imageview

There's nothing in the default TextView implementation that allows you to rotate the text. You will have to create your a custom view. Take a look at this question: Vertical (rotated) label in Android.

In that case, I think it'd be much easier to modify the bitmap representation of the ImageView and add the rotated text (which you can do using the Canvas methods like rotate, restore, etc... you can easily find information about that on Google).

Vertical Textview in Android

Finally I got it working

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:baselineAligned="false"
android:weightSum="4"
android:layout_below="@+id/offers_view">

<com.example.app.views.VerticalTextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="@+id/one"
android:text="Delhi Agra"
android:textSize="@dimen/textsize_large"
android:textColor="@color/white"
android:textAllCaps="true"
android:layout_weight="1"
android:background="#CC4D9E59"
android:layout_gravity="center"
android:gravity="right|center_horizontal"
android:paddingRight="@dimen/margin_lmedium"/>

<com.example.app.views.VerticalTextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="Goa"
android:id="@+id/two"
android:textSize="@dimen/textsize_large"
android:textColor="@color/white"
android:textAllCaps="true"
android:background="#CC9C27B0"
android:layout_weight="1"
android:gravity="left|center_horizontal"
android:paddingLeft="@dimen/logo_size"/>

<com.example.app.views.VerticalTextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="@+id/three"
android:text="Delhi"
android:textSize="@dimen/textsize_large"
android:textColor="@color/white"


Related Topics



Leave a reply



Submit