android定義style
1. 如何在android style文件中使用自定義屬性
在android style文件中使用自定義屬性是為了方便,只需要這里寫一次就可以在布局文件中多次調用,使用方法如下圖:
1、首先使用android studio打開一個項目,如下圖:
2. android 可以在程序代碼中設置style嗎
Style是View中一些屬性的集合,包括height,padding,fontcolor,background等等,Style單獨定義在xml文件中,類似與web頁面中css的角色,將設計和內容分開,便於修改和重復使用。
1 定義Style
style文件需要保存在res/values目錄下,文件名任意,但是必須是xml文件,sytle文件的根標記必須是<resources>。寫了一個簡單示例,效果如下:
請參考android學習手冊,例子、源碼、文檔全部搞定,採用androidstudo的目錄結構,360手機助手中下載。下面是截圖。
main.xml文件代碼:
<?xmlversion="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
style="@style/CodeFont"
android:text="測試style">
</TextView>
</LinearLayout>
聲明style是CodeFont,對應的是style文件中的style name。mystyle.xml文件中定義了style name是CodeFont:
parent屬性表示style之間可以繼承,同時可以覆蓋parent style的一些屬性。
<?xmlversion="1.0" encoding="utf-8"?>
<resources>
<style name="CodeFont"parent="@android:style/TextAppearance.Medium">
<itemname="android:layout_width">fill_parent</item>
<itemname="android:layout_height">wrap_content</item>
<itemname="android:textColor">#00FF00</item>
<itemname="android:typeface">monospace</item>
</style>
</resources>
2 Style的繼承
style繼承有兩種方式:
style的繼承可以通過parent屬性,用來繼承android已經定義好的style,例如:
<style name="GreenText" parent="@android:style/TextAppearance">
<itemname="android:textColor">#00FF00</item>
</style>
繼承了android中的TextAppearance,同時覆蓋了android:textColor屬性。
如果要繼承自定義的style,不需要通過parent屬性,只要style的name以需要繼承的style的name開始後跟新的style的name,中間用「.」隔開。注意:這種方式只適用與自定義的style繼承。
<style name="CodeFont.Red">
<itemname="android:textColor">#FF0000</item>
</style>
新的style繼承了CodeFont,則在修改上邊例子中的main.xml為:
<?xmlversion="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
style="@style/CodeFont.Red"
android:text="測試style">
</TextView>
</LinearLayout>
style也可以多級繼承:
<stylename="CodeFont.Red.Big">
<itemname="android:textSize">30sp</item>
</style> sytle的更多屬性見android包下的R.attr。需要注意,並不是所有的View都支持定義的style的屬性,如果自定義的sytle中包含View不支持的屬性,程序會自動忽略它。
3. android怎樣寫style
在values文件夾下的styles中添加類似
<style name="Button_style" >
<item name="android:textColor">@android:color/white</item>
<item name="android:textSize">18sp</item>
<item name="android:singleLine">true</item>
<item name="android:ellipsize">marquee</item>
<item name="android:gravity">center</item>
</style>
中間的item可以自己添加想要的效果
然後在Button中屬性添加style="@style/Button_style"!
4. android 可以在程序代碼中設置style嗎
可以的,步驟如下:
1、在項目的values/styles.xml文件里定義style屬性