Android開發(fā)中給我們提供了豐富的控件支持,可是產(chǎn)品是不斷地發(fā)展更新的笼平,產(chǎn)品經(jīng)理的想法有時(shí)候也是比較BUG的园骆。當(dāng)軟件對(duì)UI設(shè)計(jì)的要求比較高的時(shí)候,經(jīng)常會(huì)遇到安卓自帶的控件無法滿足自己需求的情況寓调,這種時(shí)候锌唾,我們只能去自己去實(shí)現(xiàn)適合項(xiàng)目的控件。同時(shí)夺英,安卓也允許你去繼承已經(jīng)存在的控件或者實(shí)現(xiàn)你自己的控件以便優(yōu)化界面和創(chuàng)造更加豐富的用戶體驗(yàn)晌涕。
在Android的UI界面都是由View和ViewGroup,及其派生類組合而成的痛悯!基于AndroidUI的設(shè)計(jì)原理余黎,按道理,我們是完全可以按照自己的意愿開發(fā)出項(xiàng)目中所需要的UI界面的载萌!View是所有UI界面的基類剧劝,包括ViewGroup也是繼承自View懊蒸,如果說一個(gè)View是一個(gè)控件,那么ViewGroup就是容納這些控件的一個(gè)容器。
根據(jù)圖充坑,作為容器的ViewGroup可以包含作為葉子節(jié)點(diǎn)的View孤紧,也可以包含作為更低層次的子ViewGroup汁讼,而子ViewGroup又可以包含下一層 的葉子節(jié)點(diǎn)的View和ViewGroup玄货。事實(shí)上,這種靈活的View層次結(jié)構(gòu)可以形成非常復(fù)雜的UI布局瓤帚,開發(fā)者可據(jù)此設(shè)計(jì)描姚、開發(fā)非常精致的UI界面涩赢。
下面就讓我來給大家介紹一下,如何來書寫這三種自定義控件轩勘!請(qǐng)隨意吐槽
- 自定義屬性attrs.xml的使用
- 基于原生控件的擴(kuò)展(例子:實(shí)現(xiàn)與系統(tǒng)字體不同的TextView)
- 基于組合控件的擴(kuò)展(例子:構(gòu)建可以圖文混排的LinearLayout)
- 自定義View(例子:波浪加載動(dòng)畫)
自定義屬性attrs.xml的使用
attrs.xml是自定義屬性的xml文件筒扒,主要作用是通過xml布局里面設(shè)置的參數(shù)然后可以傳送到程序中,我們可以理解為绊寻,attrs.xml是xml布局和java代碼中參數(shù)傳遞的橋梁花墩!
-
在values文件夾中新建一個(gè)attrs.xml文件
<pre>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MineTextView">
<attr name="color" format="color"/>
<attr name="size" format=""/>
</declare-styleable>
</resources>
</pre> -
新建一個(gè)類繼承自TextView并重載它的構(gòu)造方法,再聲明兩個(gè)變量來存儲(chǔ)自定義控件的屬性澄步,通過TypedArray獲取xml布局中的屬性值
<pre>
public class MineTextView extends TextView {
private Context context;
private float size;
private int color;public MineTextView(Context context) {
super(context);
initAttrs(context,null);
}public MineTextView(Context context, AttributeSet attrs) {
super(context, attrs,0);
initAttrs(context,attrs);
}public MineTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initAttrs(context,attrs);
}/**
- 初始化Attrs參數(shù)
*/
private void initAttrs(Context context, AttributeSet attrs) {
this.context = context;
if (attrs == null) return;
TypedArray typed = context.obtainStyledAttributes(attrs, R.styleable.MineTextView);
color = typed.getColor(R.styleable.MineTextView_color, 0X00FF00);
size = typed.getFloat(R.styleable.MineTextView_size, 32f);
typed.recycle();//使用完記得調(diào)用recycle
initView();
}
/**
- 初始化頁面
*/
public void initView(){
setTextColor(color);
setTextSize(size);
}
}
</pre>
- 初始化Attrs參數(shù)
在xml布局里面設(shè)置自定義控件屬性
在根布局容器內(nèi)添加xmlns:app = "http://schemas.android.com/apk/res-auto"
其中app是你自定義的命名空間冰蘑,res-auto是由程序自動(dòng)找資源,添加自定義控件進(jìn)去Layout里面村缸,再寫多一個(gè)正常的TextView用來做對(duì)比
<pre>
<com.marco.minecomponents.MineTextView
android:text="Hello World!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:color="@color/colorPrimary"
app:size="45"/>
<TextView
android:text="我是正常的TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</pre>
效果如下:
- 基于原生控件的擴(kuò)展(例子:實(shí)現(xiàn)與系統(tǒng)字體不同的TextView)
Android系統(tǒng)默認(rèn)支持三種字體祠肥,分別為:“****sans”, “serif”, “monospace",除此之外還可以使用其他字體文件(*.ttf)
首先在上一個(gè)Textview的里面新建一個(gè)更改字體的方法并放進(jìn)initView里面梯皿,效果如下
try {
Typeface face = Typeface.createFromAsset(context.getAssets(),"/FZLTCXHJW.TTF");
setTypeface(face);
}catch (Exception e){
e.printStackTrace();
Log.i("ddd","error--->"+e.getMessage());
}
我把字體文件放在assets文件夾下面仇箱,之后在xml布局里面添加幾個(gè)系統(tǒng)支持的字體樣式
<TextView
android:text="normal"
android:typeface="normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:text="sans"
android:typeface="sans"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:text="serif"
android:typeface="serif"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:text="monospace"
android:typeface="monospace"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
-
基于組合控件的擴(kuò)展(例子:構(gòu)建圖文混排的LinearLayout)
網(wǎng)上很多都是使用TextView.fromHtml里面的imageGetter來實(shí)現(xiàn)圖文混排,這里只是為大家簡(jiǎn)單介紹如何寫自定義控件东羹,有興趣的可以查一下相關(guān)資料剂桥!這里會(huì)給大家演示一下如何來做一個(gè)單行文本單行圖片的LinearLayoutDemo
2.1 我們新建一個(gè)Data類用來存儲(chǔ)數(shù)據(jù)類型和View
private int type;//內(nèi)容的類型: 1 圖片 2 文本
private View view;
public Data(int type, View view) {
this.type = type;
this.view = view;
}
2.2 創(chuàng)建MineLinearLayout類繼承自LinearLayout,重寫三個(gè)構(gòu)造方法和聲明一個(gè)存儲(chǔ)Data的數(shù)組作為數(shù)據(jù)源
我們先寫一個(gè)LinearLayout布局属提,因?yàn)榭紤]到我們的LinearLayout有可能高度越界权逗,所以在xml外面要封裝多一個(gè)ScrollView
<pre>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"><LinearLayout
android:id="@+id/lin"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
</ScrollView>
</pre>
2.3 之后在MineLinearLayout里面將xml的布局作為root視圖,并獲取其中的LinearLayout對(duì)象, 順便說下下面代碼的三個(gè)參數(shù)代表什么意思吧垒拢!
LayoutInflater.from(context).inflate(R.layout.layout_mine, this, true);
第一個(gè)R.layout.layout_mine, 跳過不說
第二個(gè)this旬迹,代表返回的View的父布局火惊,一般都是用null求类,在這里用this是因?yàn)槲冶緛砭屠^承了一個(gè)LinearLayout
第三個(gè)是一個(gè)boolean類型,是否將返回的View作為root視圖
之后再在MineLinearLayout里面完善添加數(shù)據(jù)屹耐,更新數(shù)據(jù)尸疆,刪除數(shù)據(jù)的操作
<pre>// 初始化頁面
public void initView(Context context) {
setOrientation(VERTICAL);//豎向分布
LayoutInflater.from(context).inflate(R.layout.layout_mine, this, true);
lin = (LinearLayout)findViewById(R.id.lin);
}
// 更新頁面public void updateView() {
for (Data data : datas) {
lin.addView(data.getView());
}
}
// 移除View
public void removeView(int position) {
if (position < datas.size() && position > 0) {
lin.removeView(datas.get(position).getView());
datas.remove(position); }
}
// 重設(shè)頁面
public void resetData() {
lin.removeAllViews();
datas.clear();
}
// 設(shè)置頁面數(shù)據(jù)
public void setData(ArrayList<Data> datas) {
resetData();
this.datas.addAll(datas);
updateView();
}
// 添加頁面數(shù)據(jù)
public void addData(Data data) {
datas.add(data);
lin.addView(data.getView());
}</pre>
2.4 在MainActivity的布局里面添加自定義控件,并添加測(cè)試數(shù)據(jù)
<pre><com.marco.minecomponents.MineLinearLayout
android:id="@+id/mine"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"/></pre>
<pre>public void initData(){
ArrayList<Data> datas = new ArrayList<>();
datas.add(new Data(0,getTextView()));
datas.add(new Data(1,getImageView()));
datas.add(new Data(0,getTextView()));
datas.add(new Data(1,getImageView()));
datas.add(new Data(0,getTextView()));
datas.add(new Data(1,getImageView()));
lin.setData(datas);
}public View getTextView() {
TextView tv = new TextView(this);
tv.setText("text");
tv.setTextSize(32);
tv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
tv.setPadding(8, 8, 8, 8);
return tv;
}public View getImageView() {
ImageView img = new ImageView(this);
img.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
img.setBackgroundResource(android.R.color.transparent);
img.setImageResource(R.drawable.demo);
return img;
}
</pre>
-
自定義View(例子:波浪動(dòng)畫)
制作一個(gè)自定義的波浪動(dòng)畫惶岭,首先是需要先畫一條曲線寿弱,我們需要使用到Android繪圖Api,其中比較重要的是Paint按灶,Path症革,和重寫onDraw方法。而繪制波浪主要是用Path提供的quadTo方法來繪制貝塞爾曲線鸯旁,其中quadTo的四個(gè)參數(shù)噪矛,分別為起始點(diǎn)的xy坐標(biāo)和終點(diǎn)的xy坐標(biāo)量蕊!在設(shè)置的時(shí)候,要把頂點(diǎn)和終點(diǎn)計(jì)算出來艇挨。
3.1 聲明要用的變量残炮,通過onSizeChange方法獲取視圖寬高,設(shè)置畫筆缩滨,在onDraw里面設(shè)置路徑势就,根據(jù)路徑來繪制曲線
<pre>
// 初始化畫筆
private void initPaint() {
paint = new Paint();
paint.setStrokeWidth(14);//設(shè)置畫筆寬度
paint.setColor(Color.argb(70, 255, 255, 255));
paint.setAntiAlias(true);//抗鋸齒
paint.setStyle(Paint.Style.STROKE);//實(shí)線
path = new Path();
}@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);//畫路徑 path.moveTo(0, mHeight / 2); path.quadTo(mWidth / 8, mHeight / 2 - waveHeight, mWidth / 4, mHeight / 2); path.quadTo(mWidth * 3 / 8, mHeight / 2 + waveHeight, mWidth / 2, mHeight / 2); path.quadTo(mWidth * 5 / 8, mHeight / 2 - waveHeight, mWidth * 3 / 4, mHeight / 2); path.quadTo(mWidth * 7 / 8, mHeight / 2 + waveHeight, mWidth, mHeight / 2); canvas.drawPath(path, paint);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
//獲取屏幕高度和寬度
this.mHeight = h;
this.mWidth = w;
}
</pre>
3.2 繪制閉合曲線
<pre>
paint.setStyle(Paint.Style.FILL);
path.lineTo(mWidth,mHeight);
path.lineTo(0,mHeight);
path.close();</pre>
3.3 下一步我們要做的就是讓路徑運(yùn)動(dòng)起來,波浪其實(shí)就是曲線向前運(yùn)動(dòng)而已脉漏!那么我們考慮如果有兩倍長(zhǎng)的曲線苞冯,當(dāng)向前運(yùn)動(dòng)的距離和寬度一致的時(shí)候,是不是就可以模擬一個(gè)波浪的動(dòng)畫了侧巨!
下面我們來看一張圖
看右上角抱完,兩端波浪組成的,所以起始位置就在(0-mWidth+movePath刃泡,mHeight/2)
而第一段波浪因?yàn)檫€在屏幕外巧娱,所以需要涉及到橫坐標(biāo)的都要家還是那個(gè)movePath-mWidth,第二段加上movePath就可以了
那么烘贴,代碼經(jīng)過修改后就變成這樣:::
<pre> //畫路徑
path.moveTo(movePath - mWidth, mHeight / 2);
path.quadTo(mWidth / 8 + movePath - mWidth, mHeight / 2 - waveHeight, mWidth / 4 + movePath - mWidth, mHeight / 2);
path.quadTo(mWidth * 3 / 8 + movePath - mWidth, mHeight / 2 + waveHeight, mWidth / 2 + movePath - mWidth, mHeight / 2);
path.quadTo(mWidth * 5 / 8 + movePath - mWidth, mHeight / 2 - waveHeight, mWidth * 3 / 4 + movePath - mWidth, mHeight / 2);
path.quadTo(mWidth * 7 / 8 + movePath - mWidth, mHeight / 2 + waveHeight, mWidth + movePath - mWidth, mHeight / 2);
//第二段
path.quadTo(mWidth / 8 + movePath, mHeight / 2 - waveHeight, mWidth / 4 + movePath, mHeight / 2);
path.quadTo(mWidth * 3 / 8 + movePath, mHeight / 2 + waveHeight, mWidth / 2 + movePath, mHeight / 2);
path.quadTo(mWidth * 5 / 8 + movePath, mHeight / 2 - waveHeight, mWidth * 3 / 4 + movePath, mHeight / 2);
path.quadTo(mWidth * 7 / 8 + movePath, mHeight / 2 + waveHeight, mWidth + movePath, mHeight / 2);
//閉合曲線
path.lineTo(mWidth + movePath, mHeight);
path.lineTo(movePath - mWidth, mHeight);
path.close();
//繪制曲線
canvas.drawPath(path, paint);</pre>
3.4 最后調(diào)用invalidate();重繪就可以了禁添,至于動(dòng)圖我就不傳了,不知道怎么傳=白佟@锨獭!囧
最終結(jié)語:其實(shí)自定義控件博大精深锻离,遠(yuǎn)遠(yuǎn)不止這么簡(jiǎn)單铺峭!這里只是說了一下我了解到的一下簡(jiǎn)單的技巧!自定義View里面的比較重要的方法例如汽纠,onMeasure卫键,onLayout,矩陣變換虱朵,我都沒說(我也沒懂)莉炉!大家將就著看吧,如果哪里有寫錯(cuò)或者不明白的碴犬,歡迎各種丟香蕉丟西瓜皮絮宁!