자산 폴더에 글꼴을 사용하여 ActionBar 제목 텍스트 (탭 텍스트가 아닌)에 사용자 정의 글꼴을 설정하는 방법은 무엇입니까? android : logo 옵션을 사용하고 싶지 않습니다.
답변
이것이 완전히 지원되지는 않는다는 데 동의하지만 여기에 내가 한 일이 있습니다. 작업 표시 줄에 대한 사용자 정의보기를 사용할 수 있습니다 (아이콘과 작업 항목 사이에 표시됨). 사용자 정의보기를 사용하고 있으며 기본 제목이 비활성화되어 있습니다. 내 모든 활동은 단일 활동에서 상속되며 onCreate 에이 코드가 있습니다.
this.getActionBar().setDisplayShowCustomEnabled(true);
this.getActionBar().setDisplayShowTitleEnabled(false);
LayoutInflater inflator = LayoutInflater.from(this);
View v = inflator.inflate(R.layout.titleview, null);
//if you need to customize anything else about the text, do it here.
//I'm using a custom TextView with a custom font in my layout xml so all I need to do is set title
((TextView)v.findViewById(R.id.title)).setText(this.getTitle());
//assign the view to the actionbar
this.getActionBar().setCustomView(v);
그리고 내 레이아웃 xml (위 코드의 R.layout.titleview)은 다음과 같습니다.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent" >
<com.your.package.CustomTextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:textSize="20dp"
android:maxLines="1"
android:ellipsize="end"
android:text="" />
</RelativeLayout>
답변
사용자 정의 TypefaceSpan
클래스를 사용하여이 작업을 수행 할 수 있습니다 . customView
액션 뷰 확장과 같은 다른 액션 바 요소를 사용할 때 깨지지 않기 때문에 위에 표시된 접근 방식 보다 우수합니다 .
이러한 클래스를 사용하면 다음과 같이 보일 것입니다.
SpannableString s = new SpannableString("My Title");
s.setSpan(new TypefaceSpan(this, "MyTypeface.otf"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// Update the action bar title with the TypefaceSpan instance
ActionBar actionBar = getActionBar();
actionBar.setTitle(s);
사용자 정의 TypefaceSpan
클래스에는 활동 컨텍스트와 assets/fonts
디렉토리 의 서체 이름이 전달 됩니다. 파일을로드하고 새 Typeface
인스턴스를 메모리에 캐시합니다 . 전체 구현 TypefaceSpan
은 놀랍도록 간단합니다.
/**
* Style a {@link Spannable} with a custom {@link Typeface}.
*
* @author Tristan Waddington
*/
public class TypefaceSpan extends MetricAffectingSpan {
/** An <code>LruCache</code> for previously loaded typefaces. */
private static LruCache<String, Typeface> sTypefaceCache =
new LruCache<String, Typeface>(12);
private Typeface mTypeface;
/**
* Load the {@link Typeface} and apply to a {@link Spannable}.
*/
public TypefaceSpan(Context context, String typefaceName) {
mTypeface = sTypefaceCache.get(typefaceName);
if (mTypeface == null) {
mTypeface = Typeface.createFromAsset(context.getApplicationContext()
.getAssets(), String.format("fonts/%s", typefaceName));
// Cache the loaded Typeface
sTypefaceCache.put(typefaceName, mTypeface);
}
}
@Override
public void updateMeasureState(TextPaint p) {
p.setTypeface(mTypeface);
// Note: This flag is required for proper typeface rendering
p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
@Override
public void updateDrawState(TextPaint tp) {
tp.setTypeface(mTypeface);
// Note: This flag is required for proper typeface rendering
tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
}
위의 클래스를 프로젝트에 복사하고 위와 같이 액티비티의 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);
답변
Android Support Library v26 + Android Studio 3.0 부터이 프로세스는 간단합니다!
툴바 제목의 글꼴을 변경하려면 다음 단계를 따르십시오.
- 다운로드 가능한 글꼴을 읽고 목록에서 글꼴을 선택 하거나 ( 내 권장 사항 ) XML의 글꼴에
res > font
따라 사용자 정의 글꼴을로드하십시오. -
에 다음
res > values > styles
을 붙여 넣습니다 ( 상상력을 여기에 사용하십시오! )<style name="TitleBarTextAppearance" parent="android:TextAppearance"> <item name="android:fontFamily">@font/your_desired_font</item> <item name="android:textSize">23sp</item> <item name="android:textStyle">bold</item> <item name="android:textColor">@android:color/white</item> </style>
-
app:titleTextAppearance="@style/TextAppearance.TabsFont"
아래와 같이 툴바 속성에 새 줄을 삽입하십시오<android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:titleTextAppearance="@style/TitleBarTextAppearance" app:popupTheme="@style/AppTheme.PopupOverlay"/>
-
Custom Actionbar Title 글꼴 스타일링을 즐기십시오!
답변
서예 라이브러리하자 당신은 또한 작업 표시 줄에 적용 할 응용 프로그램 테마를 통해 사용자 정의 글꼴을 설정합니다.
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:textViewStyle">@style/AppTheme.Widget.TextView</item>
</style>
<style name="AppTheme.Widget"/>
<style name="AppTheme.Widget.TextView" parent="android:Widget.Holo.Light.TextView">
<item name="fontPath">fonts/Roboto-ThinItalic.ttf</item>
</style>
서예를 활성화하는 데 필요한 것은 활동 컨텍스트에 첨부하는 것입니다.
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(new CalligraphyContextWrapper(newBase));
}
기본 사용자 정의 속성은 fontPath
이지만 Application 클래스에서로 초기화하여 경로에 대한 사용자 정의 속성을 제공 할 수 있습니다 CalligraphyConfig.Builder
. 사용을 android:fontFamily
권장하지 않습니다.
답변
추악한 해킹이지만 action_bar_title이 숨겨져 있기 때문에 다음과 같이 할 수 있습니다.
try {
Integer titleId = (Integer) Class.forName("com.android.internal.R$id")
.getField("action_bar_title").get(null);
TextView title = (TextView) getWindow().findViewById(titleId);
// check for null and manipulate the title as see fit
} catch (Exception e) {
Log.e(TAG, "Failed to obtain action bar title reference");
}
이 코드는 GINGERBREAD 이후 장치 용이지만 작업 표시 줄 Sherlock과 함께 작동하도록 쉽게 확장 할 수 있습니다.
PS @pjv 의견을 기반으로 액션 바 제목 ID를 찾는 더 좋은 방법이 있습니다
final int titleId =
Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
답변
다음 코드는 모든 버전에서 작동합니다. 진저 브레드가있는 장치와 JellyBean 장치에서 이것을 확인했습니다.
private void actionBarIdForAll()
{
int titleId = 0;
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
{
titleId = getResources().getIdentifier("action_bar_title", "id", "android");
}
else
{
// This is the id is from your app's generated R class when ActionBarActivity is used for SupportActionBar
titleId = R.id.action_bar_title;
}
if(titleId>0)
{
// Do whatever you want ? It will work for all the versions.
// 1. Customize your fonts
// 2. Infact, customize your whole title TextView
TextView titleView = (TextView)findViewById(titleId);
titleView.setText("RedoApp");
titleView.setTextColor(Color.CYAN);
}
}