Can't format action bar Title

2019-07-17 23:58发布

问题:

This is probably a really simple question to answer but at the moment I can't sort it.

I have my action set up as follows:

// get action bar
ActionBar actionBar = getSupportActionBar();

// set up the action bar layout
final ViewGroup actionBarLayout = (ViewGroup) getLayoutInflater().inflate(R.layout.actionbar_layout,null);

// apply layout
actionBar.setCustomView(actionBarLayout);

I have tried to set up the action bar title as follows:

  // setting action bar title
  actionBar.setTitle(getResources().getString(R.string.testing_title));

That applies the title correctly, the problem is testing_title is formatted in the strings file as follows:

 <string name = "testing_title"><b>Testing</b>Testing</string>

So the first 'Testing' should be bold and the second normal. The problem is that neither are emboldened. Would anyone know what I should do here?

In my action bar custom layout I had a text view which I was using to display the title and found an answer on here similar to this:

  private void setActionBarTitle(String title, ActionBar ab)
    {
        View v = ab.getCustomView();
        TextView titleTxtView = (TextView) v.findViewById(R.id.actionBarTitle);
        titleTxtView.setText(title);
    }

I then called this like so:

setActionBarTitle(getResources().getString(R.string.audioWalks_title), actionBar);

This however didn't produce any results. If anyone could be on any help I'd appreciate it.

回答1:

The error must be here

// setting action bar title
actionBar.setTitle(getResources().getString(R.string.testing_title));

The java.lang.String can't contain spans. Try getting the CharSequence reference.

actionBar.setTitle(getResources().getText(R.string.testing_title));


回答2:

As I suggested in the comment, I would recommend to use the Html.fromHtml(String) method. You can still keep the Strings in your resource, that's why I said decode ;)

So I found something very interessting for you on android-developers. If you are not using formatted numbers, you just need to do this:

private void setActionBarTitle(String title, ActionBar ab)
{
    View v = ab.getCustomView();
    TextView titleTxtView = (TextView) v.findViewById(R.id.actionBarTitle);
    titleTxtView.setText(Html.fromHtml(title));
}


回答3:

Try with this :

private void setActionBarTitle(String title, ActionBar ab)
    {
        View v = ab.getCustomView();
        TextView titleTxtView = (TextView) v.findViewById(R.id.actionBarTitle);
        titleTxtView.setTypeface(null, Typeface.BOLD);
        titleTxtView.setText(title);
    }