Wie kann (wenn möglich) eine benutzerdefinierte Schriftart in einem ActionBar-Titeltext (nur - nicht im Registerkartentext) mit einer Schriftart in meinem Assets-Ordner festgelegt werden? Ich möchte die Android: logo-Option nicht verwenden.
Ich stimme zu, dass dies nicht vollständig unterstützt wird, aber ich habe Folgendes getan. Sie können eine benutzerdefinierte Ansicht für Ihre Aktionsleiste verwenden (diese wird zwischen Ihrem Symbol und Ihren Aktionselementen angezeigt). Ich verwende eine benutzerdefinierte Ansicht und der native Titel ist deaktiviert. Alle meine Aktivitäten erben von einer einzigen Aktivität, die diesen Code in onCreate enthält:
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);
Und mein Layout-XML (R.layout.titleview im obigen Code) sieht folgendermaßen aus:
<?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>
Sie können dies mit einer benutzerdefinierten TypefaceSpan
-Klasse tun. Es ist dem oben angegebenen customView
-Ansatz überlegen, da es bei Verwendung anderer Aktionsleistenelemente wie dem Erweitern von Aktionsansichten nicht zerbrochen wird.
Die Verwendung einer solchen Klasse würde ungefähr so aussehen:
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);
Der benutzerdefinierten TypefaceSpan
-Klasse werden Ihr Aktivitätskontext und der Name einer Schriftart in Ihrem assets/fonts
-Verzeichnis übergeben. Es lädt die Datei und speichert eine neue Typeface
-Instanz im Speicher. Die vollständige Implementierung von TypefaceSpan
ist überraschend einfach:
/**
* 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);
}
}
Kopieren Sie einfach die obige Klasse in Ihr Projekt und implementieren Sie sie wie oben gezeigt in der onCreate
-Methode Ihrer Aktivität.
int titleId = getResources().getIdentifier("action_bar_title", "id",
"Android");
TextView yourTextView = (TextView) findViewById(titleId);
yourTextView.setTextColor(getResources().getColor(R.color.black));
yourTextView.setTypeface(face);
Ab Android Support Library v26 + Android Studio 3.0 ist dieser Vorgang ein Kinderspiel !!
Gehen Sie folgendermaßen vor, um die Schriftart des Symbolleistentitels zu ändern:
res > font
gemäß Schriftarten in XMLFügen Sie in res > values > styles
Folgendes ein (verwenden Sie Ihre Phantasie hier!)
<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>
Fügen Sie in den Eigenschaften der Symbolleiste app:titleTextAppearance="@style/TextAppearance.TabsFont"
eine neue Zeile ein (siehe unten)
<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"/>
Viel Spaß beim Custom Actionbar Title-Stil!
In der Bibliothek Calligraphy können Sie über das App-Design eine benutzerdefinierte Schriftart festlegen, die auch für die Aktionsleiste gilt.
<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>
Um Kalligraphie zu aktivieren, müssen Sie sie nur an Ihren Aktivitätskontext anfügen:
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(new CalligraphyContextWrapper(newBase));
}
Das benutzerdefinierte Standardattribut ist fontPath
. Sie können jedoch auch ein eigenes benutzerdefiniertes Attribut für den Pfad angeben, indem Sie es in Ihrer Anwendungsklasse mit CalligraphyConfig.Builder
initialisieren. Von der Verwendung von Android:fontFamily
wurde abgeraten.
Es ist ein hässlicher Hack, aber du kannst es so machen (da action_bar_title verborgen ist):
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");
}
Dieser Code ist für Gingerbread-Geräte gedacht, kann jedoch problemlos mit der Actionbar Sherlock erweitert werden
P.S. Basierend auf dem Kommentar von @pjv gibt es eine bessere Möglichkeit, die ID-Nummer der Aktionsleiste zu finden
final int titleId =
Resources.getSystem().getIdentifier("action_bar_title", "id", "Android");
verwenden Sie die neue Symbolleiste in der Unterstützungsbibliothek, um Ihre Aktionsleiste als Ihre eigene zu gestalten, oder verwenden Sie den folgenden Code
Das Aufblasen von Textview ist keine gute Option. Versuchen Sie den Builder für Spannbare Zeichenfolge
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);
kopie unter Klasse
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);
}
}
Der folgende Code funktioniert für alle Versionen. Ich habe dies in einem Gerät mit Gingerbread sowie auf einem JellyBean-Gerät überprüft
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);
}
}
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);
Ich habe gerade folgendes in der onCreate () - Funktion ausgeführt:
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);
Ich verwende die Support Libraries. Wenn Sie diese nicht verwenden, sollten Sie auf getActionBar () statt auf getSupportActionBar () umsteigen.
In Android Studio 3 können Sie mithilfe dieser Anweisungen benutzerdefinierte Schriftarten hinzufügen https://developer.Android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html und anschließend Ihre neu verwenden Schriftart in "font_to_be_used" hinzugefügt
Wenn Sie alle TextViews in der gesamten Aktivität als Schriftart festlegen möchten, können Sie Folgendes verwenden:
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);
}
Und der TypefaceCache:
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));
}
}
Es ist keine benutzerdefinierte Textansicht erforderlich!
Deaktivieren Sie zunächst den Titel in der Toobar in Ihrem Java-Code: getSupportActionBar (). setDisplayShowTitleEnabled (false);
Dann fügen Sie einfach eine TextView in die Symbolleiste ein:
<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>
Um @ Sam_Ds Antwort hinzuzufügen, musste ich Folgendes tun, damit es funktioniert:
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();
Es scheint wie Overkill - Verweise v.findViewById (R.id.title)) zweimal - aber das ist die einzige Möglichkeit, die es mir erlaubt.
Um die richtige Antwort zu aktualisieren.
erstens: Setzen Sie den Titel auf "false", da wir die benutzerdefinierte Ansicht verwenden
actionBar.setDisplayShowTitleEnabled(false);
zweitens: Erstellen Sie 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>
Zuletzt :
//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
}
FONT-DATEI HERUNTERLADEN: Weil ich die Datei in Cloudinary abspeichere, habe ich einen Link zum Herunterladen.
/**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;
}
}
}
}
Um dies zu erreichen, müssen wir Reflexionen verwenden
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) {
}
}
Kopieren Sie einfach eine gestaltete Schriftart von einer Website wie https://igfonts.io/ und fügen Sie sie ein.
Dann müssen Sie in strings.xml nur noch den Titelnamen ändern.
<resources>
<string name="app_name">???????????????? ???????? ????????????????????</string> // Title name
<string name="action_settings">Settings</string>
<string name="title_activity_item_info">ItemInfo</string>
</resources>
Versuchen Sie es mit This
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);