findViewById为action_bar_title返回null

时间:2014-11-18 09:46:35

标签: android android-actionbar android-support-library

我尝试将自定义字体设置为ActionBar标题:How to Set a Custom Font in the ActionBar Title?。所以在活动onCreate中:

int titleId = getResources().getIdentifier("action_bar_title", "id", "android");
TextView yourTextView = (TextView) findViewById(titleId);
yourTextView.setTextColor(getResources().getColor(R.color.black));
yourTextView.setTypeface(face);

findViewById会返回null。为什么呢?

我正在使用支持库:

import android.support.v7.app.ActionBarActivity;

2 个答案:

答案 0 :(得分:2)

似乎在Lollipop中被打破了。如果您正在使用工具栏,请不要知道是否有最佳选择,但您可以做这样的事情:

import android.content.Context;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import org.apache.commons.lang3.reflect.FieldUtils;

public class MyToolbar extends Toolbar {

    protected TextView mmTitleTextView;

    public MyToolbar(Context context) {
        super(context);
    }

    public MyToolbar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyToolbar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    // API

    public TextView getTitleTextView() {
        if (mmTitleTextView == null) {
            try {
                mmTitleTextView = (TextView) FieldUtils.readField(this, "mTitleTextView", true);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return mmTitleTextView;
    }
}

关于你的活动:

private MyToolbar mActionBarToolbar;
protected Toolbar getActionBarToolbar() {
    if (mActionBarToolbar == null) {
        mActionBarToolbar = (FWToolbar) findViewById(R.id.toolbar_actionbar);
        if (mActionBarToolbar != null) {
            setSupportActionBar(mActionBarToolbar);
        }
    }
    return mActionBarToolbar;
}
@Override
public void setContentView(int layoutResID) {
    super.setContentView(layoutResID);

    getActionBarToolbar();
}
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);

    if (mActionBarToolbar != null) {
        Typeface typeface = Typeface.createFromAsset(c.getAssets(), "fonts/font.ttf");
        mActionBarToolbar.getTitleTextView().setTypeface(typeface);
    }
}

答案 1 :(得分:2)

我在尝试使用支持库设置操作栏标题的内容描述时遇到了类似的问题。这里的答案对我有用:how to reference ActionBar title View on Lollipop

您可以间接检索所需的TextView,因为标题TextView没有资源ID,如下所示:

Toolbar toolbar = (Toolbar) findViewById(R.id.action_bar);
TextView textView = (TextView) toolbar.getChildAt(0);