編輯:關於 Android 程式設計
在實際開發中,系統提供的現成視圖往往無法滿足特定需求,這時我們就需要自己創建自定義 View。做法很簡單:繼承現有的 View(或它的子類),然後重寫需要的方法即可。
以下示例繼承 TextView,並在構造方法中把文字顏色設為藍色:
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setTextColor(Color.BLUE); // 將字體設置為藍色
}
}
完成後,就可以在布局文件中直接使用這個自定義 View:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.myviewtest.MyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>
如果希望像 android:layout_height="wrap_content" 那樣自定義屬性,就需要用到 declare-styleable。它專門用於為自定義控件添加自定義屬性。
首先在 res/values 目錄下新建 myAttrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyTextView">
<attr name="fontSize" format="dimension" />
</declare-styleable>
</resources>
其中:
在布局文件裡,需要通過 xmlns 聲明指向 R.java 所在包的命名空間:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:mytextview="https://schemas.android.com/apk/res/com.example.myviewtest"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.example.myviewtest.MyTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
mytextview:fontSize="20dp"
android:text="text size = 20dp" />
<com.example.myviewtest.MyTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
mytextview:fontSize="15dp"
android:text="text size=15dp" />
</LinearLayout>
其中 xmlns:mytextview 的地址指向 R.java 所在的包目錄。
最後在 MyTextView 中通過 TypedArray 讀取並應用自定義屬性的值:
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyTextView);
this.setTextSize(ta.getDimension(R.styleable.MyTextView_fontSize, 10));
ta.recycle();
}
public MyTextView(Context context) {
super(context);
}
}
通過以上四步,就完成了一個帶自定義屬性的可複用 View 組件。
Android Service 使用全解析:啟動、綁定、生命週期與進程通信
什麼是 Service Service 是 Android 四大組件之一,主要承擔耗時的後台邏輯,或者需要長期駐留的輪詢任務。即使 Activity 退出,Service
ScrollView 嵌套 ListView 的三種解法與推薦方案
實作專案時幾乎一定會遇到這個經典問題:ScrollView 裡面塞 ListView,結果列表只顯示一項,或者內容被截斷、滑動衝突。下面整理三種常見解法,並說明各自的取捨
Android 自定義 View:單行上下滾動公告
在許多 App 首頁,公告欄會以單行方式持續上下輪播。看似簡單,其實需要處理文字切換、動畫位移與定時更新。 實作思路 可以自訂一個 LinearLayout,內部放置兩
魅族 mSupport 遠程協助怎麼用?讓技術顧問直接幫你處理
對煤油(魅友)來說,mSupport 遠程支援是個容易被忽略的服務。只要手機能連上 Wi-Fi,就能讓魅族的技術支援顧問遠端接手,處理各類軟體與設定問題,不必自己在網路上