I searched a lot but can not find a way, How can I set then title at center of ActionBar instead of left aligned. I used below code to set the title at center :
ViewGroup decorView= (ViewGroup) this.getWindow().getDecorView();
LinearLayout root= (LinearLayout) decorView.getChildAt(0);
FrameLayout titleContainer= (FrameLayout) root.getChildAt(0);
TextView title= (TextView) titleContainer.getChildAt(0);
title.setGravity(Gravity.CENTER);
But it gives error as below :
ClassCastException : com.android.internal.widget.ActionBarView can not
be cast to android.widget.TextView.
Any other solution ..Any help will be appreciated.
This question is related to
android
android-actionbar
alignment
center
title
Check out new Tool bar on support library class in Lollipop update you can design actionbar by adding toolbar in your layout
add these items in your app theme
<item name="android:windowNoTitle">true</item>
<item name="windowActionBar">false</item>
Create your toolbar in a layout and include your textview in center design your toolbar
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/acbarcolor">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/app_name"
android:textColor="#ffffff"
android:textStyle="bold" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
add your action bar as tool bar
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
please ensure that you need to include toolbar on your resource file like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<include
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="@layout/toolbar" />
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="@layout/homepageinc" />
</FrameLayout>
<fragment
android:id="@+id/fragment1"
android:layout_gravity="start"
android:name="com.shouldeye.homepages.HomeFragment"
android:layout_width="250dp"
android:layout_height="match_parent" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
You can force the toolbar by wrapping title and level right padding which has default left padding for title. Than put background color to the parent of toolbar and that way part which is cut out by wrapping title is in the same color(white in my example):
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="wrap_content"
android:layout_height="56dp"
android:layout_gravity="center_horizontal"
android:paddingEnd="15dp"
android:paddingRight="15dp"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:titleTextColor="@color/black"/>
</android.support.design.widget.AppBarLayout>
Java code:
write this in onCreate()
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.action_bar);
and for you custom view, simply use FrameLayout, east peasy!
android.support.v7.widget.Toolbar is another option
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/app_name"
android:textColor="@color/black"
android:id="@+id/textView" />
</FrameLayout>
It seems there is no way to do this without custom view. You can get the title view:
View decor = getWindow().getDecorView();
TextView title = (TextView) decor.findViewById(getResources().getIdentifier("action_bar_title", "id", "android"));
But changing of gravity
or layout_gravity
doesn't have an effect.
The problem in the ActionBarView
, which layout its children by itself so changing of layout params of its children also doesn't have an effect.
To see this excecute following code:
ViewGroup actionBar = (ViewGroup) decor.findViewById(getResources().getIdentifier("action_bar", "id", "android"));
View v = actionBar.getChildAt(0);
ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
p.gravity= Gravity.CENTER;
v.setLayoutParams(p);
v.setBackgroundColor(Color.BLACK);
I think by positioning views on action bar you will reach what you want.On action bar's layout when layout params set to match parent it does not match full width that's why I did it programmatically where I succeed.By setting width (it works like layout_weight="value") we can set our view wherever we want:
actionBar = getSupportActionBar();
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater ll = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout linearLayout = (LinearLayout) ll.inflate(R.layout.custom_actionbar, null);
//inner layout within above linear layout
LinearLayout inner = (LinearLayout) linearLayout.findViewById(R.id.inner_linear_ractionbar);
inner.setMinimumWidth(getWidth() * 2 / 10);
// we will set our textview to center and display there some text
TextView t = (TextView) linearLayout.findViewById(R.id.center_text);
t.setWidth(getWidth() * 6 / 10);
Button b = (Button) linearLayout.findViewById(R.id.edit_button);
b.setWidth(getWidth() *3/ 20);
ImageButton imageButton = (ImageButton) linearLayout.findViewById(R.id.action_bar_delete_item);
imageButton.setMinimumWidth(deviceUtils.getWidth() / 20);
and here is getWidth() method:
public int getWidth() {
DisplayMetrics dm = new DisplayMetrics();
mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
return dm.widthPixels;
}
After two days of going through the web, this is what I came up with in Kotlin. Tested and works on my app
private fun setupActionBar() {
supportActionBar?.apply {
displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
displayOptions = ActionBar.DISPLAY_SHOW_TITLE
setDisplayShowCustomEnabled(true)
title = ""
val titleTextView = AppCompatTextView(this@MainActivity)
titleTextView.text = getText(R.string.app_name)
titleTextView.setSingleLine()
titleTextView.textSize = 24f
titleTextView.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.appWhite))
val layoutParams = ActionBar.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT
)
layoutParams.gravity = Gravity.CENTER
setCustomView(titleTextView, layoutParams)
setBackgroundDrawable(
ColorDrawable(
ContextCompat.getColor(
this@MainActivity,
R.color.appDarkBlue
)
)
)
}
}
This actually works:
getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getActionBar().setCustomView(R.layout.custom_actionbar);
ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
p.gravity = Gravity.CENTER;
You have to define custom_actionbar.xml layout which is as per your requirement e.g. :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#2e2e2e"
android:orientation="vertical"
android:gravity="center"
android:layout_gravity="center">
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/top_banner"
android:layout_gravity="center"
/>
</LinearLayout>
solution is based on these things:
what does it do:
when first time toolbar is executing #setTitle, it creates AppCompatTextView and uses it to display title text.
when the AppCompatTextView is created, toolbar (as ViewGroup), adds it into it's own hierarchy with #addView method.
also, while trying to find solution i noticed that the textview has layout width set to "wrap_content", so i decided to make it "match_parent" and assign textalignment to "center".
MyToolbar.kt, skipping unrelated stuff (constructors/imports):
class MyToolbar : Toolbar {
override fun addView(child: View, params: ViewGroup.LayoutParams) {
if (child is TextView) {
params.width = ViewGroup.LayoutParams.MATCH_PARENT
child.textAlignment= View.TEXT_ALIGNMENT_CENTER
}
super.addView(child, params)
}
}
possible "side effects" - this will apply to "subtitle" too
I know my answer is not on time but this is purely code no xml
required.
This is for use in Activity
public void setTitle(String title){
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
TextView textView = new TextView(this);
textView.setText(title);
textView.setTextSize(20);
textView.setTypeface(null, Typeface.BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(getResources().getColor(R.color.white));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(textView);
}
This is for use in Fragment
public void setTitle(String title){
((AppCompatActivity)getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
TextView textView = new TextView(getActivity());
textView.setText(title);
textView.setTextSize(20);
textView.setTypeface(null, Typeface.BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(getResources().getColor(R.color.white));
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
((AppCompatActivity)getActivity()).getSupportActionBar().setCustomView(textView);
}
I had the same problem, and because of the "Home" button added automatically in the toolbar, my text was not exactly entered.
I fixed it the dirty way but it works well in my case. I simply added a margin to the right of my TextView to compensate for the home button on the left. Here's my toolbar layout :
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:elevation="1dp"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
android:gravity="center"
android:background="@color/mainBackgroundColor"
android:fitsSystemWindows="true" >
<com.lunabee.common.utils.LunabeeShadowTextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="?attr/actionBarSize"
android:gravity="center"
style="@style/navigation.toolbar.title" />
</android.support.v7.widget.Toolbar>
if You are Using Toolbar the just Add
android:layout_gravity="center_horizontal"
Under the Toolbar Just like this snippet
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay">
<TextView
android:id="@+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" //Important
android:textColor="@color/whitecolor"
android:textSize="20sp"
android:textStyle="bold" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
Source: Stackoverflow.com