我以編程方式創建了一個textView。有沒有一種方法可以設置這個textView的風格?類似的東西如何以編程方式設置textView的樣式?
style="@android:style/TextAppearance.DeviceDefault.Small"
如果我有一個layout.xml文件,我會使用它。
我以編程方式創建了一個textView。有沒有一種方法可以設置這個textView的風格?類似的東西如何以編程方式設置textView的樣式?
style="@android:style/TextAppearance.DeviceDefault.Small"
如果我有一個layout.xml文件,我會使用它。
您無法以編程方式設置視圖的樣式,但您可能可以執行類似textView.setTextAppearance(context, android.R.style.TextAppearance_Small);
的操作。
此方法被標記爲已棄用。 – pkuszewski 2016-02-05 13:50:46
使用'if(Build.VERSION.SDK_INT <23){textView.setTextAppearance(context,android.R.style。TextAppearance_Small); } else { textView.setTextAppearance(android.R.style.TextAppearance_Small); }' – Nedko 2016-02-09 15:38:18
目前不可能以編程方式設置View的樣式。
要解決這個問題,你可以創建一個指定樣式的模板佈局xml文件,例如在res/layout
創建tvtemplate.xml
與以下內容:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is a template"
style="@android:style/TextAppearance.DeviceDefault.Small" />
然後充氣這個實例化新的TextView:
TextView myText = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null);
我喜歡這個解決方案比接受的答案更好,因爲它支持OP要求的樣式(我想要)。此外,它總是感覺如此....錯誤....使用android.widget構造函數。 – 2015-08-26 12:45:31
在運行時(在代碼中),您可以通過風格構造產生意見:View(Context, AttributeSet, int)
在你要調用其他情況下VARIOS方法來改變外觀
試試這個
textview.setTextAppearance(context, R.style.yourstyle);
這可能無法正常嘗試使用像這樣的textview創建一個xml
textviewstyle.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="@android:style/TextAppearance.DeviceDefault.Small" />
爲了獲得所需的樣式膨脹包含的TextView
TextView myText = (TextView)getLayoutInflater().inflate(R.layout.tvstyle, null);
其實XML,這是可能的API級別的21
的TextView有一個4 parameter constructor:
TextView (Context context,
AttributeSet attrs,
int defStyleAttr,
int defStyleRes)
中間兩個在這種情況下參數不是必需的。下面的代碼直接在活動中創建一個TextView,只定義了它的樣式資源:
TextView myStyledTextView = new TextView(this, null, 0, R.style.my_style);
@Deprecated
public void setTextAppearance(Context context, @StyleRes int resId)
這種方法已被棄用由於Android SKD 23
,你可以使用安全的版本:
if (Build.VERSION.SDK_INT < 23) {
super.setTextAppearance(context, resId);
} else {
super.setTextAppearance(resId);
}
您不能務實地設置任何視圖的樣式。但你可以設置視圖的個別屬性 – 2013-02-22 08:53:37
可能重複[Android - 以編程方式設置TextView TextStyle?](http://stackoverflow.com/questions/7919173/android-set-textview-textstyle-programmatically) – 2016-12-02 09:31:10