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

问题描述:

我有很多不同的称呼为工具栏,我是从以前的活动低谷意图传递的:如何改变工具栏的高度和字体大小以编程根据文本长度的

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

我将它们设置为我的新的工具栏活动是这样的:

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

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

ŧ他是例如标题之一:雷达范围传播KILOMETER到微秒时间 转换,反之亦然

我想知道有没有适合这个标题的方式来动态改变工具栏的高度和文字大小?这可以通过编程方式

感谢

试试这个创建自定义工具栏这样

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

有没有办法做到这一点编程? 另外,当文本较长时,我需要缩小字体大小... –

+0

是的,这是可能的 –

+0

我将使用您的答案,因为我没有设法通过编程实现,并且我采用了我的代码。此外,字体现在更小,并且可以始终适合。 –

你可以尝试这样的:

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