編輯:關於Android編程
筆者之前已經寫過了一些自定義View的文章,在此對其也就不從頭說起了,如有興趣的讀者可以看一下筆者的前兩篇文章。
筆者之前的文章中僅僅介紹了如何使用自定義View以及為什麼要使用自定義View等等,但是在實際操作中,我們還是希望自定義View之後,直接能夠在xml中就對其進行操作,如下圖:


主要代碼:

首先要在values文件中創建一個xml文件,並且在其中寫上你需要的自定義屬性的名稱以及類型。

atts.xml中代碼如下:<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwcmUgY2xhc3M9"brush:java;">
此點比較簡單,直接看代碼:
MyView.java
package com.example.double2.viewxmltest;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* 項目名稱:ViewXmlTest
* 創建人:Double2號
* 創建時間:2016/8/4 10:23
* 修改備注:
*/
public class MyView extends LinearLayout {
private int colorText;
private String textLeft;
private String textTitle;
private String textRight;
private TextView tvLeft;
private TextView tvTitle;
private TextView tvRight;
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//從xml的屬性中獲取到字體顏色與string
TypedArray ta=context.obtainStyledAttributes(attrs,R.styleable.MyTitle);
colorText=ta.getColor(R.styleable.MyTitle_textColor,Color.BLACK);
textLeft=ta.getString(R.styleable.MyTitle_leftText);
textTitle=ta.getString(R.styleable.MyTitle_titleText);
textRight=ta.getString(R.styleable.MyTitle_rightText);
ta.recycle();
//獲取到控件
//加載布局文件,與setContentView()效果一樣
LayoutInflater.from(context).inflate(R.layout.my_view, this);
tvLeft=(TextView)findViewById(R.id.tv_left);
tvTitle=(TextView)findViewById(R.id.tv_title);
tvRight=(TextView)findViewById(R.id.tv_right);
//將控件與設置的xml屬性關聯
tvLeft.setTextColor(colorText);
tvLeft.setText(textLeft);
tvTitle.setTextColor(colorText);
tvTitle.setText(textTitle);
tvRight.setTextColor(colorText);
tvRight.setText(textRight);
}
}
my_view.xml
此處要注意在activity_main.xml要申明第三方命名空間(在android studio中只需要用res-auto,在eclipse中就需要加上完整的包名,如下圖)
注:my_view只是使用時的一個名稱而已,後方的“http://schemas.android.com/apk/res-auto”才是真正有用的。


activity_main.xml
如何預置Android 手機 APK
預制APK有以下4種情況: 1, 如何將帶源碼的 APK 預置進系統? 2, 如何將無源碼的APK預置進系統? 3, 如何預置APK使得用戶可以卸載,恢復出廠設置時不能恢
android:模擬水波效果的自定義View
歡迎Fork,歡迎Star1.先看效果2.再看關鍵代碼描繪函數y = Asin(wx+d)+offset /** * 使用路徑描繪繪制的區域 *
Android學習筆記4 Activity的生命周期
1 activity的聲明周期 安卓程序的最重要三個狀態為Resumed/Paused/Stopped, 絕大多數時間程序都會在這3個狀態間切換. 安卓程
Android WebP 圖片壓縮與傳輸
1. 簡介直到4g時代,流量依然是寶貴的東西。而移動網絡傳輸中,最占流量的一種載體:圖片,成為了我們移動開發者不得不關注的一個問題。我們關注的問題,無非是圖片體積和質量如