如何根据文本长度以编程方式更改工具栏高度和字体大小

时间:2017-08-10 11:25:41

标签: android android-toolbar

我有很多不同的Toolbar标题,我从之前的活动通过意图传递:

title = getIntent().getStringExtra("title");

我将它们设置为我的新活动工具栏,如下所示:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle(title);

但字体太大,只覆盖一行工具栏: enter image description here

这是一个示例标题: 将雷达范围传播千米转换为微观时间和VICE-VERSA

我想知道有没有办法动态更改Toolbar高度和文字大小以适应此标题?这可以通过编程方式完成吗?

由于

2 个答案:

答案 0 :(得分:3)

尝试创建像这样的自定义工具栏

 <android.support.v7.widget.Toolbar
     android:id="@+id/toolbar"
     android:layout_width="match_parent"
     android:layout_height="?attr/actionBarSize"
     android:background="?attr/colorPrimary"
     app:popupTheme="@style/AppTheme.PopupOverlay">

        <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Did you know"
            android:id="@+id/myTitle"
            android:textColor="@android:color/white" />
    </LinearLayout>
</android.support.v7.widget.Toolbar>

并将您的活动主题用作NoActionBar

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView myTitle = (TextView) toolbar.findViewById(R.id.myTitle);

答案 1 :(得分:1)

您可以尝试这样:

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="@color/action_bar_bkgnd"
app:theme="@style/ToolBarTheme" >


 <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Toolbar Title"
    android:layout_gravity="center"
    android:id="@+id/toolbar_title" />


</android.support.v7.widget.Toolbar>

并在java文件中;

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_top);
TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title);
相关问题