Пользовательский шрифт для вкладок ActionBarSherlock
Я хочу установить шрифт для вкладок "Видео" и "Изображение" в ActionBarSherlock
. Для этого я использовал следующий код. Его точное отображение в ICS, но не в устройстве с более низкой версией, но я показал точный вывод в другой части этого приложения, установив TYPE FACE, как...
a.settypeface("ab.tttf");
a.settext("VIDEO");
Но как сделать, я установил TypeFace
в ActionBar
в этом коде:
mTabsAdapter.addTab(bar.newTab().setText("IMAGE"), AFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText("VIDEO"), BFragment.class, null);
Ответы
Ответ 1
Хорошо. Я сам нашел его где-то на SO.
Сначала создайте xml файл с этим в нем: tab_title.xml
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/action_custom_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My Custom title"
android:textColor="#fff"
android:textSize="18sp"
android:paddingTop="5dp" />
Затем в классе, где вы создаете экземпляр вашего ActionBar, используйте этот код, чтобы установить текст на каждой вкладке. (В этом примере используется ActionBarSherlock.)
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
String[] tabNames = {"Tab 1","Tab 2","Tab 3"};
for(int i = 0; i<bar.getTabCount(); i++){
LayoutInflater inflater = LayoutInflater.from(this);
View customView = inflater.inflate(R.layout.tab_title, null);
TextView titleTV = (TextView) customView.findViewById(R.id.action_custom_title);
titleTV.setText(tabNames[i]);
//Here you can also add any other styling you want.
bar.getTabAt(i).setCustomView(customView);
}
Ответ 2
Чтобы решить эту проблему, вы можете создать класс Special Actionbar.
Просто создайте класс myBar extends Sherlockactionbar
и поместите в settypeface. Если теперь вы создадите эту панель, у вас будет Typeface, как вы это делаете. Например, вот кнопка с новым шрифтом.
public class ChangedButton extends Button{
public ChangedButton(Context context, AttributeSet attrs) {
super(context, attrs);
Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/viking2.TTF");
this.setTypeface(font);
}
}
рассматривает
Ответ 3
Попробуйте следующее:
String s = "VIDEO";
SpannableString mSS = new SpannableString(s);
mSS.setSpan(new StyleSpan(Typeface.BOLD), 0, s.length(), 0);
mTabsAdapter.addTab(bar.newTab().setText(mSS),
BFragment.class, null);
Ответ 4
Сначала создайте в своем проекте следующий класс TypefaceSpan
. Вы изменили версию Custom TypefaceSpan, чтобы использовать как .otf
, так и .ttf
шрифты.
import java.util.StringTokenizer;
import android.content.Context;
import android.graphics.Typeface;
import android.support.v4.util.LruCache;
import android.text.TextPaint;
import android.text.style.MetricAffectingSpan;
public class TypefaceSpan extends MetricAffectingSpan{
/*Cache to save loaded fonts*/
private static LruCache<String, Typeface> typeFaceCache= new LruCache<String, Typeface>(12);
private Typeface mTypeface;
public TypefaceSpan(Context context,String typeFaceName)
{
StringTokenizer tokens=new StringTokenizer(typeFaceName,".");
String fontName=tokens.nextToken();
mTypeface=typeFaceCache.get(fontName);
if(mTypeface==null)
{
mTypeface=Constants.getFont(context, typeFaceName);
//cache the loaded font
typeFaceCache.put(fontName, mTypeface);
}
}
@Override
public void updateMeasureState(TextPaint p) {
p.setTypeface(mTypeface);
}
@Override
public void updateDrawState(TextPaint tp) {
tp.setTypeface(mTypeface);
}
}
Теперь примените код следующим образом: (Я использовал это в одном из приложений Bangla успешно)
SpannableString mstKnwTitle=new SpannableString(getString(R.string.e_mustknow_tab));
SpannableString cntctsTitle=new SpannableString(getString(R.string.e_number_tab));
TypefaceSpan span=new TypefaceSpan(this, "solaimanlipi.ttf");
mstKnwTitle.setSpan(span, 0, mstKnwTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
cntctsTitle.setSpan(span, 0, mstKnwTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Tab tab= actionBar.newTab();
tab.setText(mstKnwTitle);
tab.setTabListener(tabListener);
actionBar.addTab(tab);
tab= actionBar.newTab();
tab.setText(cntctsTitle);
tab.setTabListener(tabListener);
actionBar.addTab(tab);
Оригинальное вдохновение в моем ответе было: Стилизация заголовка панели действий Android с использованием пользовательского шрифта
Ответ 5
Похоже, вы не получаете никаких указаний. Я не уверен в моем ответе, но да, вы можете вызывающе получить идею сделать это, как хотите.
Позвольте мне попытаться помочь вам. Я думаю, вам нужно немного поиграть со встроенными ресурсами по умолчанию для android sdk.
Вам нужно создать собственный стиль:
<style name="MyActionBarTabText" parent="Widget.ActionBar.TabText">
<item name="android:textAppearance">@style/TextAppearance.Holo.Medium</item>
<item name="android:textColor">?android:attr/textColorPrimary</item>
<item name="android:textSize">12sp</item>
<item name="android:textStyle">bold</item>
<item name="android:textAllCaps">true</item>
<item name="android:ellipsize">marquee</item>
<item name="android:maxLines">2</item>
</style>
<style name="Widget.ActionBar.TabText" parent="Widget">
<item name="android:textAppearance">@style/TextAppearance.Widget.TextView.PopupMenu</item>
<item name="android:textColor">?android:attr/textColorPrimaryInverse</item>
<item name="android:textSize">18sp</item>
<item name="android:fontFamily">HERE YOU CAN GIVE YOUR FONT</item>
</style>
Вы также можете ссылаться на this SO.
Теперь примените эту тему к своей деятельности, и вы получите шрифт TabText, как хотите.
Прокомментируйте, если у вас есть какие-либо вопросы.
Наслаждайтесь кодированием...:)
В EXTRA
Другим решением может быть изменение изображения вкладки, чтобы включить текст, GIMP или что-то в Photoshop, а затем просто установите эти изображения в вкладках вместо изображений и текста. Это немного неудобный способ сделать это, но это сработает.
Надеюсь, это поможет!
Ответ 6
Вы можете сделать это с помощью этого:
// Set a custom font on all of our ActionBar Tabs
private boolean setCustomFontToActionBarTab(Object root) {
// Found the container, that holds the Tabs. This is the ScrollContainerView to be specific,
// but checking against that class is not possible, since it part of the hidden API.
// We will check, if root is an instance of HorizontalScrollView instead,
// since ScrollContainerView extends HorizontalScrollView.
if (root instanceof HorizontalScrollView) {
// The Tabs are all wraped in a LinearLayout
root = ((ViewGroup) root).getChildAt(0);
if (root instanceof LinearLayout) {
// Found the Tabs. Now we can set a custom Font to all of them.
for (int i = 0; i < ((ViewGroup) root).getChildCount(); i++) {
LinearLayout child = ((LinearLayout)((ViewGroup) root).getChildAt(i));
TextView actionBarTitle = (TextView) child.getChildAt(0);
Typeface tf = Typeface.createFromAsset(mContext.getAssets(), "font/font.ttf");
actionBarTitle.setTypeface(tf)
}
return true;
}
}
// Search ActionBar and the Tabs. Exclude the content of the app from this search.
else if (root instanceof ViewGroup) {
ViewGroup group = (ViewGroup) root;
if (group.getId() != android.R.id.content) {
// Found a container that isn't the container holding our screen layout.
// The Tabs have to be in here.
for (int i = 0; i < group.getChildCount(); i++) {
if (setCustomFontToActionBarTab(group.getChildAt(i))) {
// Found and done searching the View tree
return true;
}
}
}
}
// Found nothing
return false;
}
Вызвать это следующим образом:
ViewParent root = findViewById(android.R.id.content).getParent();
setCustomFontToActionBarTab(root);