Android開發中給我們提供了豐富的控件支持,可是產品是不斷地發展更新的,產品經理的想法有時候也是比較BUG的。當軟件對UI設計的要求比較高的時候,經常會遇到安卓自帶的控件無法滿足自己需求的情況,這種時候,我們只能去自己去實現適合項目的控件。同時,安卓也允許你去繼承已經存在的控件或者實現你自己的控件以便優化界面和創造更加豐富的用戶體驗。
在Android的UI界面都是由View和ViewGroup,及其派生類組合而成的!基于AndroidUI的設計原理,按道理,我們是完全可以按照自己的意愿開發出項目中所需要的UI界面的!View是所有UI界面的基類,包括ViewGroup也是繼承自View,如果說一個View是一個控件,那么ViewGroup就是容納這些控件的一個容器。
根據圖,作為容器的ViewGroup可以包含作為葉子節點的View,也可以包含作為更低層次的子ViewGroup,而子ViewGroup又可以包含下一層 的葉子節點的View和ViewGroup。事實上,這種靈活的View層次結構可以形成非常復雜的UI布局,開發者可據此設計、開發非常精致的UI界面。
下面就讓我來給大家介紹一下,如何來書寫這三種自定義控件!請隨意吐槽
- 自定義屬性attrs.xml的使用
- 基于原生控件的擴展(例子:實現與系統字體不同的TextView)
- 基于組合控件的擴展(例子:構建可以圖文混排的LinearLayout)
- 自定義View(例子:波浪加載動畫)
自定義屬性attrs.xml的使用
attrs.xml是自定義屬性的xml文件,主要作用是通過xml布局里面設置的參數然后可以傳送到程序中,我們可以理解為,attrs.xml是xml布局和java代碼中參數傳遞的橋梁!
-
在values文件夾中新建一個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> -
新建一個類繼承自TextView并重載它的構造方法,再聲明兩個變量來存儲自定義控件的屬性,通過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參數
*/
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();//使用完記得調用recycle
initView();
}
/**
- 初始化頁面
*/
public void initView(){
setTextColor(color);
setTextSize(size);
}
}
</pre>
- 初始化Attrs參數
在xml布局里面設置自定義控件屬性
在根布局容器內添加xmlns:app = "http://schemas.android.com/apk/res-auto"
其中app是你自定義的命名空間,res-auto是由程序自動找資源,添加自定義控件進去Layout里面,再寫多一個正常的TextView用來做對比
<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>
效果如下:
- 基于原生控件的擴展(例子:實現與系統字體不同的TextView)
Android系統默認支持三種字體,分別為:“****sans”, “serif”, “monospace",除此之外還可以使用其他字體文件(*.ttf)
首先在上一個Textview的里面新建一個更改字體的方法并放進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布局里面添加幾個系統支持的字體樣式
<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"
/>
-
基于組合控件的擴展(例子:構建圖文混排的LinearLayout)
網上很多都是使用TextView.fromHtml里面的imageGetter來實現圖文混排,這里只是為大家簡單介紹如何寫自定義控件,有興趣的可以查一下相關資料!這里會給大家演示一下如何來做一個單行文本單行圖片的LinearLayoutDemo
2.1 我們新建一個Data類用來存儲數據類型和View
private int type;//內容的類型: 1 圖片 2 文本
private View view;
public Data(int type, View view) {
this.type = type;
this.view = view;
}
2.2 創建MineLinearLayout類繼承自LinearLayout,重寫三個構造方法和聲明一個存儲Data的數組作為數據源
我們先寫一個LinearLayout布局,因為考慮到我們的LinearLayout有可能高度越界,所以在xml外面要封裝多一個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對象, 順便說下下面代碼的三個參數代表什么意思吧!
LayoutInflater.from(context).inflate(R.layout.layout_mine, this, true);
第一個R.layout.layout_mine, 跳過不說
第二個this,代表返回的View的父布局,一般都是用null,在這里用this是因為我本來就繼承了一個LinearLayout
第三個是一個boolean類型,是否將返回的View作為root視圖
之后再在MineLinearLayout里面完善添加數據,更新數據,刪除數據的操作
<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); }
}
// 重設頁面
public void resetData() {
lin.removeAllViews();
datas.clear();
}
// 設置頁面數據
public void setData(ArrayList<Data> datas) {
resetData();
this.datas.addAll(datas);
updateView();
}
// 添加頁面數據
public void addData(Data data) {
datas.add(data);
lin.addView(data.getView());
}</pre>
2.4 在MainActivity的布局里面添加自定義控件,并添加測試數據
<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(例子:波浪動畫)
制作一個自定義的波浪動畫,首先是需要先畫一條曲線,我們需要使用到Android繪圖Api,其中比較重要的是Paint,Path,和重寫onDraw方法。而繪制波浪主要是用Path提供的quadTo方法來繪制貝塞爾曲線,其中quadTo的四個參數,分別為起始點的xy坐標和終點的xy坐標!在設置的時候,要把頂點和終點計算出來。
3.1 聲明要用的變量,通過onSizeChange方法獲取視圖寬高,設置畫筆,在onDraw里面設置路徑,根據路徑來繪制曲線
<pre>
// 初始化畫筆
private void initPaint() {
paint = new Paint();
paint.setStrokeWidth(14);//設置畫筆寬度
paint.setColor(Color.argb(70, 255, 255, 255));
paint.setAntiAlias(true);//抗鋸齒
paint.setStyle(Paint.Style.STROKE);//實線
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 下一步我們要做的就是讓路徑運動起來,波浪其實就是曲線向前運動而已!那么我們考慮如果有兩倍長的曲線,當向前運動的距離和寬度一致的時候,是不是就可以模擬一個波浪的動畫了!
下面我們來看一張圖
看右上角,兩端波浪組成的,所以起始位置就在(0-mWidth+movePath,mHeight/2)
而第一段波浪因為還在屏幕外,所以需要涉及到橫坐標的都要家還是那個movePath-mWidth,第二段加上movePath就可以了
那么,代碼經過修改后就變成這樣:::
<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 最后調用invalidate();重繪就可以了,至于動圖我就不傳了,不知道怎么傳!!!囧
最終結語:其實自定義控件博大精深,遠遠不止這么簡單!這里只是說了一下我了解到的一下簡單的技巧!自定義View里面的比較重要的方法例如,onMeasure,onLayout,矩陣變換,我都沒說(我也沒懂)!大家將就著看吧,如果哪里有寫錯或者不明白的,歡迎各種丟香蕉丟西瓜皮!