【问题标题】:How to add padding to ActionBar item如何为 ActionBar 项添加填充
【发布时间】:2015-08-20 21:54:53
【问题描述】:

我为此搜索了解决方案,有人建议我在设置操作栏标题时包含空格:

actionBar.setTitle("   Ribbit");

它工作正常,像这样,但我想知道是否有更好的方法来实现这一点,例如在某处添加 android:padding xml 属性。

【问题讨论】:

  • 你的意思是想让actionBar的标题居中吗?

标签: android android-actionbar padding


【解决方案1】:

它工作正常,就像这样,但我想知道是否有更好的方法 实现这一点,例如添加 android:padding xml 某处的属性。

更好的方法是确保为您的 ActionBar 创建自定义布局(视图)(现在应该将其称为 Toolbar,因为 ActionBar 现在已弃用)。

使用自定义布局,您可以根据需要设置 ActionBar 的样式。可能性是无穷无尽的。 Here 是您可以开始的点。

【讨论】:

  • 感谢拉格纳您的回答!该链接绝对很有帮助! :)
【解决方案2】:

最好的方法是使用 Material Design Toolbar 小部件。

创建工具栏app_bar.xml 文件,你可以给你想要的名字。

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

  <!-- This textView will act as Title of page which you can make it Center or change padding/margin to change its position -->
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="30sp"
    android:paddingTop="0dp"
    android:text="Home"
    android:layout_gravity="center"
    android:id="@+id/toolbar_title" />
 </android.support.v7.widget.Toolbar>

确保您在styles.xml 中选择了主题

"Theme.AppCompat.NoActionBar"

之后,你需要在你的 mainActivity.xml 布局文件中初始化这个工具栏,包括这个,

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

然后在 MainActivity 中,您需要创建 Toolbar 工具栏的实例。然后,在 setContentView() 之后 用您的

添加以下内容
 toolbar = (Toolbar) findViewById(R.id.app_toolbar);
    setSupportActionBar(toolbar);

确保禁用

ActionBar actionBar = getSupportActionBar();    
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setDisplayShowHomeEnabled(false);

所以它不会重复工具栏的标题并从应用程序继承一个。

【讨论】:

  • 感谢 Ajay 提供详细且解释清楚的答案。我一定会尝试这种方法!我假设工具栏小部件会自动为菜单项添加必要的填充。
  • 是的,它会自动执行,但您可以根据需要将自己的 textView 作为工具栏的标题,如上面给出的示例。
猜你喜欢
  • 1970-01-01
  • 2022-07-19
  • 2019-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-06
  • 2010-10-14
相关资源
最近更新 更多