我试图找出正确的方法来使用自定义字体的工具栏标题,并在工具栏中心(客户端需求)。
目前,我正在使用好的老ActionBar,我正在设置标题为空值,并使用setCustomView把我的自定义字体TextView和中心使用ActionBar. layoutparams。
有更好的办法吗?使用新的工具栏作为我的动作栏。
我试图找出正确的方法来使用自定义字体的工具栏标题,并在工具栏中心(客户端需求)。
目前,我正在使用好的老ActionBar,我正在设置标题为空值,并使用setCustomView把我的自定义字体TextView和中心使用ActionBar. layoutparams。
有更好的办法吗?使用新的工具栏作为我的动作栏。
当前回答
一个非常快速和简单的方法来设置自定义字体是使用自定义titleTextAppearance与fontFamily:
添加到styles.xml:
<style name="ToolbarTitle" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
<item name="android:textSize">16sp</item>
<item name="android:textColor">#FF202230</item>
<item name="android:fontFamily">@font/varela_round_regular</item>
</style>
在res文件夹中创建一个字体文件夹(例如:varela_round_regular.ttf)
阅读官方指南,了解更多https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html
其他回答
我不知道appcompat库中是否有任何变化,但这是相当微不足道的,不需要反射。
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// loop through all toolbar children right after setting support
// action bar because the text view has no id assigned
// also make sure that the activity has some title here
// because calling setText() with an empty string actually
// removes the text view from the toolbar
TextView toolbarTitle = null;
for (int i = 0; i < toolbar.getChildCount(); ++i) {
View child = toolbar.getChildAt(i);
// assuming that the title is the first instance of TextView
// you can also check if the title string matches
if (child instanceof TextView) {
toolbarTitle = (TextView)child;
break;
}
}
@Composable
fun topAppBar() {
CenterAlignedTopAppBar(
title = {
Text(
"Top App Bar"
)
},
navigationIcon = {
IconButton(onClick = { /*TODO*/ }) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = "Back"
)
}
},
actions = {
IconButton(onClick = { /*TODO*/ }) {
Icon(
imageVector = Icons.Default.MoreVert,
contentDescription = "More",
)
}
},
colors = TopAppBarDefaults.smallTopAppBarColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer
)
)
}
}
我用这个问题的解决方案:
public static void applyFontForToolbarTitle(Activity a){
Toolbar toolbar = (Toolbar) a.findViewById(R.id.app_bar);
for(int i = 0; i < toolbar.getChildCount(); i++){
View view = toolbar.getChildAt(i);
if(view instanceof TextView){
TextView tv = (TextView) view;
if(tv.getText().equals(a.getTitle())){
tv.setTypeface(getRuneTypefaceBold(a));
break;
}
}
}
}
对于重心,我认为有必要将布局参数水平更改为match_parent,然后:
tv.setGravity(Gravity.CENTER);
我不知道是否有人有这个问题,但使用额外的文本视图是不好的,因为你必须自己管理标题,使用反射是最糟糕的,因为id在添加progurad规则时发生了变化。 最简单和准确的答案是使用材质工具栏,它具有标题居中的属性。
app:titleCentered
这是我用一个导航图标和一个文本视图所做的 现在您可以进行扩展,以便在任何需要的地方应用它。但你必须把它应用到每一项活动中
(toolbar[0] as AppCompatTextView).let {
it.viewTreeObserver.addOnDrawListener {
it.layoutParams = it.layoutParams.apply {
width = Toolbar.LayoutParams.MATCH_PARENT
(this as ViewGroup.MarginLayoutParams).apply {
marginEnd = toolbar[1].width
}
}
it.textAlignment = View.TEXT_ALIGNMENT_CENTER
}
}