編輯:關於 Android 程式設計
把控件的重複屬性抽成 Style,是讓布局文件保持整潔的關鍵手段。本文用一個最簡單的例子說明如何在 Android 中定義並應用自定義 Style。
文件位置:res/values/styles.xml
<resources xmlns:android="https://schemas.android.com/apk/res/android">
<style name="AppBaseTheme" parent="android:Theme.Light">
</style>
<style name="AppTheme" parent="AppBaseTheme">
</style>
<!-- 自定義樣式 -->
<style name="testStyle">
<item name="android:textSize">30px</item>
<item name="android:textColor">#1110CC</item>
<item name="android:width">150dip</item>
<item name="android:height">150dip</item>
</style>
</resources>
每個 <item> 就是一條屬性聲明,name 前面加上 android: 前綴表示使用系統內置屬性。這裡我們預設了文字大小、文字顏色、寬度和高度四項。
文件位置:res/layout/main.xml
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>
給 TextView 加上 style="@style/testStyle" 屬性即可套用(原文示例中省略了該行,實際使用時別忘了補上)。
package com.cn;
import android.os.Bundle;
import android.app.Activity;
/**
* Demo:為控件設置自定義 Style
* 步驟:
* 1. 在 styles.xml 中自定義一個 style,裡面預設文字大小、顏色、寬高等屬性
* 2. 在布局文件中為控件設置 style 屬性
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Activity 本身不需要任何額外代碼,Style 完全由資源系統在加載布局時解析,這也是它比在 Java 裡逐個 setTextSize、setTextColor 更優雅的原因。
自訂 View 實現 Shape 圖形繪製
概述 之前曾寫過一篇文章,介紹了 Android 中 drawable 使用 Shape 資源,透過定義 drawable 中的 shape 資源,能繪製矩形、橢圓形、線
Android ActionBar 詳解
介紹 ActionBar 是 Google 自 Android 3.0 起推出的全新使用者操作方式,旨在取代舊有的選單鍵與長按操作,帶來一致且便利的介面體驗,同時方便開發
Android 圖片加載優化實戰:二級緩存搭配異步加載
一、問題從哪裡來 凡是列表頁、資訊流、畫廊這類場景,幾乎都要從網路拉取大量圖片。如果每次滑動都重新發一次請求,畫面不僅容易掉幀,用戶的流量也吃不消。實務上常見的解法是「二
Android DrawerLayout 側滑布局詳解(一):基礎用法
DrawerLayout 顧名思義,就是一個用來管理布局的容器,使用方式與其他布局類別相似。它自帶滑動功能,只要按照 DrawerLayout 規定的布局方式寫好層級,就