수행줄 제목에서 사용자 지정 글꼴을 설정하는 방법?
가능한 경우 자산 폴더의 글꼴로 수행 표시줄 제목 텍스트(탭 텍스트만 아님)에서 사용자 정의 글꼴을 설정하려면 어떻게 해야 합니까?Android:logo 옵션을 사용하고 싶지 않습니다.
사용자 정의를 사용하여 이 작업을 수행할 수 있습니다.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
인스턴스(instance)입니다. 완전한 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
위와 같은 방법입니다.
저는 이것이 완전히 지원되지 않는다는 것에 동의하지만, 제가 한 일은 이렇습니다.수행 표시줄에 사용자 정의 보기를 사용할 수 있습니다(아이콘과 수행 항목 사이에 표시됨)사용자 정의 보기를 사용하고 있으며 기본 제목을 사용할 수 없습니다.모든 활동은 다음 코드가 있는 단일 활동에서 상속됩니다.
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>
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 이후로는 이 과정이 필름 작업처럼 쉬워졌습니다!!
다음 단계에 따라 도구 모음 제목의 글꼴을 변경합니다.
- 다운로드 가능한 글꼴을 읽고 목록에서 원하는 글꼴을 선택하거나(권장사항) 사용자 정의 글꼴을 로드합니다.
res > font
XML 글꼴 기준 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"/>
사용자 지정 작업 표시줄 제목 글꼴 스타일을 즐기십시오!!
캘리그라피 라이브러리에서는 앱 테마를 통해 사용자 지정 글꼴을 설정할 수 있으며, 이 글꼴은 수행 표시줄에도 적용됩니다.
<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
할 수도 .CalligraphyConfig.Builder
의 android:fontFamily
낙담했습니다.
ActionBar actionBar = getSupportActionBar();
TextView tv = new TextView(getApplicationContext());
Typeface typeface = ResourcesCompat.getFont(this, R.font.monotype_corsiva);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, // Width of TextView
RelativeLayout.LayoutParams.WRAP_CONTENT); // Height of TextView
tv.setLayoutParams(lp);
tv.setText("Your Text"); // ActionBar title text
tv.setTextSize(25);
tv.setTextColor(Color.WHITE);
tv.setTypeface(typeface, typeface.ITALIC);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setCustomView(tv);
추악한 해킹이지만 이렇게 할 수 있습니다(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");
}
이 코드는 사후 진저브레드 장치를 위한 것이지만 액션 바 셜록과 함께 작동하도록 쉽게 확장할 수 있습니다.
추신: @pjv 댓글을 기반으로 액션 바 제목 ID를 찾는 더 나은 방법이 있습니다.
final int titleId =
Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
다음 코드는 모든 버전에 적용됩니다.나는 이것을 젤리빈 장치뿐만 아니라 진저브레드가 있는 장치에서도 확인했습니다.
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);
}
}
지원 라이브러리의 새 도구 모음을 사용하여 수행 표시줄을 자신의 것으로 설계하거나 아래 코드를 사용합니다.
텍스트 보기 부풀리기는 좋은 옵션이 아닙니다. 스패너블 문자열 작성기를 사용해 보십시오.
Typeface font2 = Typeface.createFromAsset(getAssets(), "fonts/<your font in assets folder>");
SpannableStringBuilder SS = new SpannableStringBuilder("MY Actionbar Tittle");
SS.setSpan (new CustomTypefaceSpan("", font2), 0, SS.length(),Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
actionBar.setTitle(ss);
하등본
public class CustomTypefaceSpan extends TypefaceSpan{
private final Typeface newType;
public CustomTypefaceSpan(String family, Typeface type) {
super(family);
newType = type;
}
@Override
public void updateDrawState(TextPaint ds) {
applyCustomTypeFace(ds, newType);
}
@Override
public void updateMeasureState(TextPaint paint) {
applyCustomTypeFace(paint, newType);
}
private static void applyCustomTypeFace(Paint paint, Typeface tf) {
int oldStyle;
Typeface old = paint.getTypeface();
if (old == null) {
oldStyle = 0;
} else {
oldStyle = old.getStyle();
}
int fake = oldStyle & ~tf.getStyle();
if ((fake & Typeface.BOLD) != 0) {
paint.setFakeBoldText(true);
}
if ((fake & Typeface.ITALIC) != 0) {
paint.setTextSkewX(-0.25f);
}
paint.setTypeface(tf);
}
}
전체 활동의 모든 텍스트 보기에 글꼴을 설정하려면 다음과 같은 방법을 사용할 수 있습니다.
public static void setTypefaceToAll(Activity activity)
{
View view = activity.findViewById(android.R.id.content).getRootView();
setTypefaceToAll(view);
}
public static void setTypefaceToAll(View view)
{
if (view instanceof ViewGroup)
{
ViewGroup g = (ViewGroup) view;
int count = g.getChildCount();
for (int i = 0; i < count; i++)
setTypefaceToAll(g.getChildAt(i));
}
else if (view instanceof TextView)
{
TextView tv = (TextView) view;
setTypeface(tv);
}
}
public static void setTypeface(TextView tv)
{
TypefaceCache.setFont(tv, TypefaceCache.FONT_KOODAK);
}
그리고 Typeface Cache:
import java.util.TreeMap;
import android.graphics.Typeface;
import android.widget.TextView;
public class TypefaceCache {
//Font names from asset:
public static final String FONT_ROBOTO_REGULAR = "fonts/Roboto-Regular.ttf";
public static final String FONT_KOODAK = "fonts/Koodak.ttf";
private static TreeMap<String, Typeface> fontCache = new TreeMap<String, Typeface>();
public static Typeface getFont(String fontName) {
Typeface tf = fontCache.get(fontName);
if(tf == null) {
try {
tf = Typeface.createFromAsset(MyApplication.getAppContext().getAssets(), fontName);
}
catch (Exception e) {
return null;
}
fontCache.put(fontName, tf);
}
return tf;
}
public static void setFont(TextView tv, String fontName)
{
tv.setTypeface(getFont(fontName));
}
}
방금 onCreate() 함수 안에서 다음을 수행했습니다.
TypefaceSpan typefaceSpan = new TypefaceSpan("font_to_be_used");
SpannableString str = new SpannableString("toolbar_text");
str.setSpan(typefaceSpan,0, str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
getSupportActionBar().setTitle(str);
저는 지원 라이브러리를 사용하고 있습니다. 사용하지 않을 경우 getSupportActionBar() 대신 ActionBar()로 전환해야 합니다.
Android Studio 3에서 이 지침에 따라 사용자 정의 글꼴을 추가할 수 있습니다. https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html 에서 새로 추가한 글꼴을 "syslog_to_be_used"에서 사용할 수 있습니다.
사용해 보십시오.
TextView headerText= new TextView(getApplicationContext());
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
headerText.setLayoutParams(lp);
headerText.setText("Welcome!");
headerText.setTextSize(20);
headerText.setTextColor(Color.parseColor("#FFFFFF"));
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/wesfy_regular.ttf");
headerText.setTypeface(tf);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(headerText);
@Sam_D의 답변을 덧붙이자면, 저는 그것이 작동하도록 하기 위해 이것을 해야 했습니다.
this.setTitle("my title!");
((TextView)v.findViewById(R.id.title)).setText(this.getTitle());
TextView title = ((TextView)v.findViewById(R.id.title));
title.setEllipsize(TextUtils.TruncateAt.MARQUEE);
title.setMarqueeRepeatLimit(1);
// in order to start strolling, it has to be focusable and focused
title.setFocusable(true);
title.setSingleLine(true);
title.setFocusableInTouchMode(true);
title.requestFocus();
v.findViewById(R.id .title)를 두 번 참조하는 것은 오버킬처럼 보이지만, 그것이 제가 그것을 할 수 있는 유일한 방법입니다.
정답을 업데이트합니다.
먼저 : 제목을 false로 설정합니다. 왜냐하면 사용자 지정 보기를 사용하고 있기 때문입니다.
actionBar.setDisplayShowTitleEnabled(false);
두 번째 : titleview.xml을 만듭니다.
<?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" >
<TextView
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>
마지막으로:
//font file must be in the phone db so you have to create download file code
//check the code on the bottom part of the download file code.
TypeFace font = Typeface.createFromFile("/storage/emulated/0/Android/data/"
+ BuildConfig.APPLICATION_ID + "/files/" + "font name" + ".ttf");
if(font != null) {
LayoutInflater inflator = LayoutInflater.from(this);
View v = inflator.inflate(R.layout.titleview, null);
TextView titleTv = ((TextView) v.findViewById(R.id.title));
titleTv.setText(title);
titleTv.setTypeface(font);
actionBar.setCustomView(v);
} else {
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(" " + title); // Need to add a title
}
Download Font File : 파일을 cloudinary에 저장하고 있기 때문에 다운로드할 링크가 있습니다.
/**downloadFile*/
public void downloadFile(){
String DownloadUrl = //url here
File file = new File("/storage/emulated/0/Android/data/" + BuildConfig.APPLICATION_ID + "/files/");
File[] list = file.listFiles();
if(list == null || list.length <= 0) {
BroadcastReceiver onComplete = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
try{
showContentFragment(false);
} catch (Exception e){
}
}
};
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadUrl));
request.setVisibleInDownloadsUi(false);
request.setDestinationInExternalFilesDir(this, null, ModelManager.getInstance().getCurrentApp().getRegular_font_name() + ".ttf");
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
} else {
for (File files : list) {
if (!files.getName().equals("font_name" + ".ttf")) {
BroadcastReceiver onComplete = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
try{
showContentFragment(false);
} catch (Exception e){
}
}
};
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadUrl));
request.setVisibleInDownloadsUi(false);
request.setDestinationInExternalFilesDir(this, null, "font_name" + ".ttf");
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
} else {
showContentFragment(false);
break;
}
}
}
}
사용자 지정 텍스트 보기가 필요하지 않습니다!
먼저 Java 코드의 도구 모음에서 제목을 비활성화합니다. getSupportActionBar().setDisplayShowTitleEnabled(false);
그런 다음 도구 모음 내부에 TextView를 추가합니다.
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:textSize="18sp"
android:fontFamily="@font/roboto" />
</android.support.v7.widget.Toolbar>
우리는 이것을 달성하기 위해 반영을 사용할 필요가 있습니다.
final int titleId = activity.getResources().getIdentifier("action_bar_title", "id", "android");
final TextView title;
if (activity.findViewById(titleId) != null) {
title = (TextView) activity.findViewById(titleId);
title.setTextColor(Color.BLACK);
title.setTextColor(configs().getColor(ColorKey.GENERAL_TEXT));
title.setTypeface(configs().getTypeface());
} else {
try {
Field f = bar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
title = (TextView) f.get(bar);
title.setTextColor(Color.BLACK);
title.setTypeface(configs().getTypeface());
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
}
사용해 보십시오.
public void findAndSetFont(){
getActionBar().setTitle("SOME TEST TEXT");
scanForTextViewWithText(this,"SOME TEST TEXT",new SearchTextViewInterface(){
@Override
public void found(TextView title) {
}
});
}
public static void scanForTextViewWithText(Activity activity,String searchText, SearchTextViewInterface searchTextViewInterface){
if(activity == null|| searchText == null || searchTextViewInterface == null)
return;
View view = activity.findViewById(android.R.id.content).getRootView();
searchForTextViewWithTitle(view, searchText, searchTextViewInterface);
}
private static void searchForTextViewWithTitle(View view, String searchText, SearchTextViewInterface searchTextViewInterface)
{
if (view instanceof ViewGroup)
{
ViewGroup g = (ViewGroup) view;
int count = g.getChildCount();
for (int i = 0; i < count; i++)
searchForTextViewWithTitle(g.getChildAt(i), searchText, searchTextViewInterface);
}
else if (view instanceof TextView)
{
TextView textView = (TextView) view;
if(textView.getText().toString().equals(searchText))
if(searchTextViewInterface!=null)
searchTextViewInterface.found(textView);
}
}
public interface SearchTextViewInterface {
void found(TextView title);
}
언급URL : https://stackoverflow.com/questions/8607707/how-to-set-a-custom-font-in-the-actionbar-title
'programing' 카테고리의 다른 글
iframe의 현재 위치를 어떻게 알 수 있습니까? (0) | 2023.08.05 |
---|---|
유형 ORM 0.3.7 데이터 소스 연결 풀이 갑자기 닫혔습니다. (0) | 2023.08.05 |
쿼리가 두 개 이상의 행을 반환하는 경우 SQL 삭제 (0) | 2023.08.05 |
두 인수를 사용하는 크기 (0) | 2023.08.05 |
Ubuntu Server의 Apache 2.4.6: 서버 구성(PHP FPM)에 의해 클라이언트가 거부됨 [PHP 파일 로드 중] (0) | 2023.08.05 |