Android - 实用代码片段(1)

1.ColorFilter 修改图片颜色,滤镜

1
2
3
4
5
public static Drawable filtDrawable(Drawable drawable, int color) {
ColorFilter filter = new LightingColorFilter(0, color);
drawable.setColorFilter(filter);
return drawable;
}

相关文章 http://www.cnblogs.com/fuxiuyuan/archive/2012/04/14/2447545.html

2.获取StatusBar高度

1
2
3
4
5
public static float getStatusBarHeight(Activity activity) {
Resources resources = activity.getResources();
int status_bar_height_id = resources.getIdentifier("status_bar_height", "dimen", "android");
return resources.getDimension(status_bar_height_id);
}

3.获取ActionBar的视图

1
2
3
4
5
6
7
8
public static View findActionBarContainer(Activity activity) {
int id = activity.getResources().getIdentifier("action_bar_container", "id", "android");
return activity.findViewById(id);
}
public static View findSplitActionBar(Activity activity) {
int id = activity.getResources().getIdentifier("split_action_bar", "id", "android");
return activity.findViewById(id);
}

4.计算文字大小绘制需要的宽高

1
2
3
4
Rect rect = new Rect();
mPaint.getTextBounds(text, 0, text.length(), rect);
rect.width();
rect.height();

5.Activity中可以获取Actionbar上Item的View

1
getActivity().findViewById(R.id.menu_favorite); //

6.java.lang.IllegalStateException: No activity

1
2
3
4
5
6
7
8
9
10
11
12
13
@Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}

7.保存恢复ListView位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private void saveCurrentPosition() {
if (mListView != null) {
int position = mListView.getFirstVisiblePosition();
View v = mListView.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
//保存position和top
}
}
private void restorePosition() {
if (mFolder != null && mListView != null) {
int position = 0;//取出保存的数据
int top = 0;//取出保存的数据
mListView.setSelectionFromTop(position, top);
}
}

Gavin Liu wechat
欢迎您扫一扫上面的二维码,订阅我的微信公众号!