0
我有一些自定義的視圖,如:認沽視圖樣式
public class CustomizedTextView extends TextView {
...
public CustomizedTextView(Context context) {
this.setText(TEXT_COLOR);
this.setTextSize(TEXT_SIZE);
this.setTypeFace(TYPE_FACE);
this.setPadding(LEFT, TOP, RIGHT, BOTTOM);
...
}
}
正如你所看到的,這些樣式設置和相應的常數需要多行代碼。所以我想在資源文件中分離出來。
我已經通過了Android documentation,它說,你可以定義一個樣式文件,如:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CodeFont" parent="@android:style/TextAppearance.Medium">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#00FF00</item>
<item name="android:typeface">monospace</item>
</style>
</resources>
但我沒有找到喜歡的setStyle(R.style.style001)的API來設置風格碼。我也在這裏找到了一個帖子:android set style in code
基本上它說你不能在代碼中做到這一點。然而,這篇文章是在三年前,我不確定API 19中的情況如何。因爲定義一個自定義視圖在Android中非常普遍,所以我不明白爲什麼這是不可能的。
你在XML中創建或代碼這一觀點,當你將它添加到您的應用程序TextView的風格? – dharms
@dcharms我在代碼中創建它。我知道如何使用xml添加樣式,但不知道如何使用代碼添加樣式。 – darklord
您可以使用代碼中的setTextAppearance來設置樣式。看到我的答案 – Libin