Android - 实用代码片段(3)

  • 在View Layout完成后获取 控件大小
1
2
3
4
5
6
7
8
9
final TextView tv = (TextView) findViewById(R.id.myTextView);
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Toast.makeText(MyActivity.this, tv.getWidth() + " x " + tv.getHeight(), Toast.LENGTH_LONG).show();
tv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
  • 关键帧插值器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static float calculateValue(float[] values, float time, float def) {
float value = def;
if (values != null && values.length > 0) {
float segment = 1.0f / (float)(values.length - 1);
int index = (int)(time / segment);
if (index >= values.length - 1) {
value = values[values.length - 1];
} else {
float extra = time - segment * (float)index;
value = values[index] + (values[index + 1] - values[index]) * extra / segment;
}
}
return value;
}
  • 给图片叠加渐变
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private void addShadow(Bitmap bitmap, int color) {
int[] colors = new int[]{
color & 0x00FFFFFF,
color & 0x0AFFFFFF,
color & 0x33FFFFFF,
color & 0x66FFFFFF,
color & 0x99FFFFFF,
color & 0xCCFFFFFF,
color
};
GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
gradientDrawable.setGradientType(GradientDrawable.LINEAR_GRADIENT);
Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
gradientDrawable.setBounds(rect);
gradientDrawable.setLevel(8);
Canvas canvass = new Canvas(bitmap);
gradientDrawable.draw(canvass);
}
  • ListView 或者 GridView 去除滑动特性 (即固定高度)
1
2
3
4
5
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
  • 获取系统长按时间,自定义View会用到
1
getSystemLongPressTime
  • 判断设备是否有网
1
2
3
4
5
public static boolean isOnline(Context context) {
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
Gavin Liu wechat
欢迎您扫一扫上面的二维码,订阅我的微信公众号!