有這樣一個需求,需要再itemView選中或者點擊之後,給它添加一個選中效果,當然,現在開發框架那麼多,尤其是tv開發框架,用MainUpView就可以實現,但是我偏要用自定義的view實現呢?很簡單,一個方法幾句話就可以實現。
1、效果圖:
2、分析代碼:
需要自定義一個View,代碼是ElementView.java:
/**
* ElementView 2016-10-28
*/
public class ElementView extends ImageView {
/****** 畫筆工具 ******/
private Paint mPaint;
/**
* @param context
*/
public ElementView(Context context) {
super(context);
mPaint = new Paint();
// TODO Auto-generated constructor stub
}
/**
* @param context
* @param attrs
*/
public ElementView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
// TODO Auto-generated constructor stub
}
/**
* @param context
* @param attrs
* @param defStyleAttr
*/
public ElementView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mPaint = new Paint();
// TODO Auto-generated constructor stub
}
@SuppressLint({ "DrawAllocation", "NewApi" })
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
// view獲取焦點後執行
if (hasFocus()) {
// 設置畫筆抗鋸齒
mPaint.setAntiAlias(true);
// 畫筆顏色,就是邊框顏色,白色不透明(可以設置其他自己喜歡的邊框顏色),0xffffffff爲不透明,0x00ffffff爲透明
mPaint.setColor(0xffffffff);
// 設置畫筆的風格,stroke爲邊框模式,fill爲填充內部區域模式,fill_and_stroke是填充加邊框,全覆蓋
mPaint.setStyle(Style.STROKE);
// 設置畫筆邊框的寬度
mPaint.setStrokeWidth(4f);
// 設置畫筆的透明色
// mPaint.setAlpha(200);
Rect rect = new Rect();
// 獲取當前view顯示的區域座標
getGlobalVisibleRect(rect);
// getLocalVisibleRect(rect);
int left = 2;
int top = 2;
int right = rect.right - rect.left - 2;
int bottom = rect.bottom - rect.top - 2;
RectF rectf = new RectF(left, top, right, bottom);
// 用畫筆畫一個帶圓角的矩形框,3.0f爲圓角的弧度
canvas.drawRoundRect(rectf, 3.0f, 3.0f, mPaint);
// canvas.drawRect(left, top, right, bottom, mPaint);
Log.e("=====onDraw=====", "left: " + left + ",top: " + top
+ ",right: " + right + ",bottom: " + bottom);
} else {
}
}
}
可以看到hasFocus()
判斷了一下,是否獲取到了焦點,如果獲取焦點執行畫框部分代碼,然後動畫放大效果的代碼如下:
if (hasFocus) {
//view獲取焦點後執行放大動畫
// 放大,視圖動畫
Animation animation = AnimationUtils.loadAnimation(
getActivity(), R.anim.scale);
view.startAnimation(animation);
view.bringToFront();
//這裏是屬性動畫的透明度設置
// ObjectAnimator alpha = ObjectAnimator.ofFloat(view, "alpha",
// 1.0f, 0.6f, 1.0f).setDuration(1200);
// alpha.setRepeatMode(ValueAnimator.RESTART);
// alpha.setRepeatCount(ValueAnimator.INFINITE);
// alpha.start();
} else {
// 縮小
Animation animation = AnimationUtils.loadAnimation(
getActivity(), R.anim.smallscale);
view.startAnimation(animation);
}
ok,這樣就能實現如上效果圖的選中的白色框和動畫了。