如何在默认主题(Theme.Holo.Light)中将标题对齐到 ActionBar 的中心 [英] How to align title at center of ActionBar in default theme(Theme.Holo.Light)

查看:39
本文介绍了如何在默认主题(Theme.Holo.Light)中将标题对齐到 ActionBar 的中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了很多但找不到方法,如何将标题设置在 ActionBar 的中心而不是左对齐.我使用下面的代码将标题设置在中心:

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);

但它给出如下错误:

ClassCastException : com.android.internal.widget.ActionBarView can not 
be cast to android.widget.TextView.

任何其他解决方案..任何帮助将不胜感激.

Any other solution ..Any help will be appreciated.

推荐答案

您可以创建自定义布局并将其应用到 actionBar.

You can create a custom layout and apply it to the actionBar.

为此,请按照以下 2 个简单步骤操作:

To do so, follow those 2 simple steps:

  1. Java 代码

getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.actionbar);

其中 R.layout.actionbar 是以下布局.

  1. XML

<?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="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:id="@+id/action_bar_title"
    android:text="YOUR ACTIVITY TITLE"
    android:textColor="#ffffff"
    android:textSize="24sp" />
</LinearLayout>

它可以像您想要的那样复杂.试试看!

It can be as complex as you want. Try it out!

要设置background,您可以在容器布局(在这种情况下为LinearLayout)中使用属性android:background.您可能需要将布局高度 android:layout_height 设置为 match_parent 而不是 wrap_content.

To set the background you can use the property android:background in the container layout (LinearLayout in that case). You may need to set the layout height android:layout_height to match_parent instead of wrap_content.

此外,您还可以为其添加LOGO/ICON.为此,只需在您的布局中添加一个 ImageView,并将布局方向属性 android:orientation 设置为水平(或简单地使用 RelativeLayout 并自行管理).

Moreover, you can also add a LOGO / ICON to it. To do so, simply add an ImageView inside your layout, and set layout orientation property android:orientation to horizontal (or simply use a RelativeLayout and manage it by yourself).

要动态更改上述自定义操作栏的标题,请执行以下操作:

To change the title of above custom action bar dynamically, do this:

TextView title=(TextView)findViewById(getResources().getIdentifier("action_bar_title", "id", getPackageName()));
title.setText("Your Text Here");

这篇关于如何在默认主题(Theme.Holo.Light)中将标题对齐到 ActionBar 的中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆