前言
這裡積累了一些不常見确又很實用的代碼,每收集7條更新一次,希望能對大家有用。
聲明
歡迎轉載,但請保留文章原始出處:)
部落格園:http://www.cnblogs.com
農民伯伯: http://over140.cnblogs.com
正文
1、 精确擷取螢幕尺寸(例如:3.5、4.0、5.0寸螢幕)
public static double getscreenphysicalsize(activity ctx) {
displaymetrics dm = new displaymetrics();
ctx.getwindowmanager().getdefaultdisplay().getmetrics(dm);
double diagonalpixels = math.sqrt(math.pow(dm.widthpixels, 2) + math.pow(dm.heightpixels, 2));
return diagonalpixels / (160 * dm.density);
}
一般是7寸以上是平闆
2、 判斷是否是平闆(官方用法)
public static boolean istablet(context context) {
return (context.getresources().getconfiguration().screenlayout & configuration.screenlayout_size_mask) >= configuration.screenlayout_size_large;
3、 文字根據狀态更改顔色 android:textcolor
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#53c1bd" android:state_selected="true"/>
<item android:color="#53c1bd" android:state_focused="true"/>
<item android:color="#53c1bd" android:state_pressed="true"/>
<item android:color="#777777"/>
</selector>
放在res/color/目錄下
4、背景色根據狀态更改顔色 android:backgroup
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
<item android:state_selected="true"><shape>
<gradient android:angle="0" android:centercolor="#00a59f" android:endcolor="#00a59f" android:startcolor="#00a59f" />
</shape></item>
<item android:state_focused="true"><shape>
<item android:state_pressed="true"><shape>
<item><shape>
<gradient android:angle="0" android:centercolor="#00ff00" android:endcolor="00ff00" android:startcolor="00ff00" />
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
如果直接給背景色color會報錯。
5、 啟動apk的預設activity
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
public static void startapkactivity(final context ctx, string packagename) {
packagemanager pm = ctx.getpackagemanager();
packageinfo pi;
try {
pi = pm.getpackageinfo(packagename, 0);
intent intent = new intent(intent.action_main, null);
intent.addcategory(intent.category_launcher);
intent.setpackage(pi.packagename);
list<resolveinfo> apps = pm.queryintentactivities(intent, 0);
resolveinfo ri = apps.iterator().next();
if (ri != null) {
string classname = ri.activityinfo.name;
intent.setcomponent(new componentname(packagename, classname));
ctx.startactivity(intent);
}
} catch (namenotfoundexception e) {
log.e("startactivity", e);
}
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
7、計算字寬
public static float gettextwidth(string text, float size) {
textpaint fontpaint = new textpaint();
fontpaint.settextsize(size);
return fontpaint.measuretext(text);
注意如果設定了textstyle,還需要進一步設定textpaint。
轉自:http://www.cnblogs.com/over140/archive/2012/09/26/2611999.html