Skip to content

Instantly share code, notes, and snippets.

@BenDLH
Last active November 18, 2020 08:14
Show Gist options
  • Save BenDLH/5e95ca556235710d02a414257e616c78 to your computer and use it in GitHub Desktop.
Save BenDLH/5e95ca556235710d02a414257e616c78 to your computer and use it in GitHub Desktop.
The Joy of Custom Views: How to make a centered title Toolbar in Android
//
// CenteredTitleToolbar
//
// Created by Ben De La Haye on 25/05/2016.
//
public class CenteredTitleToolbar extends Toolbar {
private TextView _titleTextView;
private int _screenWidth;
private boolean _centerTitle = true;
public CenteredTitleToolbar(Context context) {
super(context);
init();
}
public CenteredTitleToolbar(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public CenteredTitleToolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
_screenWidth = DeviceUtils.getInstance().getScreenSize().x;
_titleTextView = new TextView(getContext());
_titleTextView.setTextAppearance(getContext(), R.style.ToolbarTitleText);
_titleTextView.setText("Title");
addView(_titleTextView);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (_centerTitle) {
int[] location = new int[2];
_titleTextView.getLocationOnScreen(location);
_titleTextView.setTranslationX(_titleTextView.getTranslationX() + (-location[0] + _screenWidth / 2 - _titleTextView.getWidth() / 2));
}
}
@Override
public void setTitle(CharSequence title) {
_titleTextView.setText(title);
requestLayout();
}
@Override
public void setTitle(int titleRes) {
_titleTextView.setText(titleRes);
requestLayout();
}
public void setTitleCentered(boolean centered) {
_centerTitle = centered;
requestLayout();
}
private Point getScreenSize() {
WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point screenSize = new Point();
display.getSize(screenSize);
return screenSize;
}
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="ToolbarTitleText" parent="Base.TextAppearance.Widget.AppCompat.Toolbar.Title">
<item name="android:textColor">#FFFFFF</item>
</style>
</resources>
@pavelsust
Copy link

What is DeviceUtils ??

Copy link

ghost commented Jan 11, 2019

Delete

What is DeviceUtils ??

Delete this line:
_screenWidth = DeviceUtils.getInstance().getScreenSize().x;

Replace with this:
_screenWidth = getScreenSize().x;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment