[英]Android change TextView textSize on RecyclerView adapter from Activity
[英]Android studio: change textSize on Custom extends activity
我將TextView類擴展為“ CustomTextView”,這就是為什么我需要設置自定義字體的原因。 結果如下:
public class CustomTextView extends TextView {
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/nn.otf"));
this.setTextSize(30);
}
}
您可以看到我將默認的textSize設置為30:
當我想要這個CustomTextView時,可以使用以下代碼:
<com.calendar.CustomTextView
android:id="@+id/edData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DOM 21 GIU"
android:textSize="45dp"/>
如果您注意到了,我將textSize值設置為45dp,但它仍然是30(來自自定義類)。 如何設置不同的textSize? 還有,想要大膽的風格嗎?
您應該刪除this.setTextSize(30); 從構造函數中獲取,因為xml布局會在super(context,attrs)調用期間進行大小調整,並且otf文件中應包含粗體字體(通常是不同樣式的不同otf文件)
這是我的解決方案:(我使用textColor而不是textSize進行了測試,但這是相同的)。
我編輯了res / values / atrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomTextView">
<attr name="textColor" format="string" />
</declare-styleable>
</resources>
然后,我按如下方式編輯課程:
public class CustomTextView extends TextView {
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public CustomTextView(Context context) {
super(context);
init(null);
}
private void init(AttributeSet attrs) {
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.CustomTextView);
String fontName = a.getString(R.styleable.CustomTextView_fontName);
if (textColor != null) {
this.setTextColor(Color.parseColor(textColor));
} else {
this.setTextColor(Color.parseColor("#000000"));
}
a.recycle();
}
}
}
所以這項工作:
<com.imgspa.listviewadapter.CustomTextView
android:id="@+id/ed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
listviewadapter:textColor="#FF0000"/>
<com.imgspa.listviewadapter.CustomTextView
android:id="@+id/edRis"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="35dp" />
第一個自定義textview文本為紅色,第二個為黑色
要設置樣式,只需使用android:textStyle="bold"
。 對於您的其他問題,可以使用attrs.getAttribute(NAME OF ATTRIBUTE)
方法從我認為的屬性中檢查textSize,然后將其設置為該值或根據需要將其設置為30。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.