2014-11-18 3 views
2

Я попытался установить собственный шрифт в заголовок ActionBar: How to Set a Custom Font in the ActionBar Title?. Таким образом, в деятельности onCreate:findViewById возвращает null для action_bar_title

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

Try использовать getActionBar() findViewById() ; –

+1

@HareshChhelana вы догадываетесь? Класс ActionBar не имеет метода findViewById и, кроме того, я использую библиотеку поддержки. –

+0

При использовании только findViewById ссылается на текущий макет действий, и вы пытаетесь изменить actionview TextView, чтобы можно было найти findById с помощью ссылки getActionBar(). –

ответ

2

Кажется, что сломано в леденец. Не знаю, если есть лучшая альтернатива, но вы можете сделать что-то вроде этого, если вы используете панель инструментов:

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

У меня была аналогичная проблема при попытке для установки описания содержимого заголовка панели действий, используя библиотеки поддержки. Ответ здесь работает для меня: how to reference ActionBar title View on Lollipop

Вы можете получить TextView, что вы хотите, косвенно, потому что название TextView не имеет идентификатора ресурса, например:.

Toolbar toolbar = (Toolbar) findViewById(R.id.action_bar); 
TextView textView = (TextView) toolbar.getChildAt(0); 
Смежные вопросы