我正在尝试将此标题作为TextView获取,但它不起作用:
TextView title = (TextView) findViewById(R.id.action_bar_title);
标题为空。如何使用AppCompat将标题作为TextView获取?
答案 0 :(得分:5)
通常在我的情况下使用工具栏时,如果我正在使用标题进行自定义操作,我将手动膨胀标题视图,然后在XML中设置其属性。工具栏的目的是防止这样的事情发生,这样你就可以更好地控制工具栏的样子
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/my_awesome_toolbar"
android:layout_height="@dimen/standard_vertical_increment"
android:layout_width="match_parent"
android:minHeight="@dimen/standard_vertical_increment"
android:background="@drawable/actionbar_background">
<TextView
style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:id="@+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/Red" />
</android.support.v7.widget.Toolbar>
然后在代码中,你会做这样的事情:
Toolbar toolbar = findViewById(R.id.my_awesome_toolbar);
//Get rid of the title drawn by the toolbar automatically
toolbar.setTitle("");
TextView toolbarTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
toolbarTitle.setTextColor(Color.BLUE);
答案 1 :(得分:3)
蛮力似乎是一种解决方案:
private void findTextViewTitle() {
String title = "title";
ActionBar ab = getSupportActionBar();
ab.setTitle(title);
Window window = getWindow();
View decor = window.getDecorView();
ArrayList<View> views = new ArrayList<View>();
decor.findViewsWithText(views, title, View.FIND_VIEWS_WITH_TEXT);
for (View view : views) {
Log.d(TAG, "view " + view.toString());
}
TextView tvTitle = (TextView) decor.findViewById(views.get(0).getId());
tvTitle.setBackgroundColor(Color.RED);
}
答案 2 :(得分:0)
这里是如何从ActionBar获取TextView的方法。即使ActionBar方向更改,此方法也可以确保选择TextView。如果需要,它还允许您获取图标-只需检查ImageView的子实例即可。
//If you just want to set the text
ActionBar actBar = getSupportActionBar();
if(actBar != null) {
actBar.setTitle(R.string.your_ab_title);
}
//If you want to customize more than the text
Toolbar ab = findViewById(R.id.action_bar);
if(ab != null){
for (int i= 0; i < ab.getChildCount(); i++){
if(ab.getChildAt(i) instanceof TextView) {
TextView title = (TextView) ab.getChildAt(i);
//You now have the title textView. Do something with it
title.setText("Your Custom AB Title");
}
}
}
答案 3 :(得分:0)
嘿,谢谢大家的帮助,这是我最终得到的实现。
// USAGE
Toolbar yourToolbar = (Toolbar) findViewById(R.id.your_toolbar);
TextView actionTitle = ActionBarTitle(toolbar);
actionTitle.setTypeface(font("Snake"));
// IMPLEMENTATION
private TextView ActionBarTitle(Toolbar toolbarForRead)
{
TextView title = null;
if (toolbarForRead != null)
{
for (int i= 0; i < toolbarForRead.getChildCount(); i++)
{
if (toolbarForRead.getChildAt(i) instanceof
TextView)
{
title = (TextView)
toolbarForRead.getChildAt(i);
return title;
}
}
}
return null;
}
private Typeface font(String fontName)
{
return Typeface.createFromAsset(this.getAssets(), "fonts/" + fontName + ".ttf");
}
答案 4 :(得分:0)