前言:单独开一篇将遇到的关于android代码中的一些小问题予以总结。
一、关闭软键盘
InputMethodManager inputMethodManager = (InputMethodManager)Activity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(Activity.this.getCurrentFocus().getWindowToken(), InputMethodManager.RESULT_HIDDEN);
二、dip与pix转换
在代码中涉及到的int,比如LayoutParams.setPadding(int……)与android.view.ViewGroup.LayoutParams.height、android.view.ViewGroup.LayoutParams.width这些,全部都是指的pix(像素),而在XML中,为了设备无关性,我们一般使用DIP来代替相素,所以在代码中,我们要常常用到DIP与PIX的转换,转换公式如下:
public static int dip2px(Context context, float dipValue){
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dipValue * scale + 0.5f);
}
public static int px2dip(Context context, float pxValue){
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(pxValue / scale + 0.5f);
}
相关网址:《android中dip、px相互换算》:http://www.cnblogs.com/error404/archive/2011/11/03/2234165.html
三、使textView点击变色(Selector)
首先在res目录下新建drawable文件夹,再在新建的drawable文件夹中新建mytv_view.xml,其目录结构为:res/drawable/mytv_view.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:color="#ff0000" />
<item android:state_focused="true" android:color="#ff0000" />
<item android:state_pressed="true" android:color="#ff0000" />
<item android:color="#89683B" />
</selector>
2.设置textview的selector
<TextView
android:id="@+id/Item_Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:clickable="true"
android:textColor="@color/textview" >
</TextView>
相关网址:
《Android设置TextView的Selector来控制点击的颜色》:http://kaizen.blog.51cto.com/5333370/921041
《Android中的Selector的用法》:http://blog.csdn.net/shakespeare001/article/details/7788400
三、获取当前APP所在手机的IP和MAC地址:
调用Android的API: WifiManager
权限:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
获取MAC地址:
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
return info.getMacAddress();
获取IP地址:
public static String getCurIp(WifiManager wifiManager)
{
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
return ( ipAddress & 0xFF) +"."+
((ipAddress >> 8 ) & 0xFF) + "." +
((ipAddress >> 16 ) & 0xFF) + "." +
((ipAddress >> 24 ) & 0xFF );
}
四、设置textview行间距
XML:
android:lineSpacingExtra
android:lineSpacingMultiplier
JAVA:
setLineSpacing(float,float)
五、android程序更换图标安装后不变解决办法
我们有些手机安装了老版本的应用后,当应用更换图标后,在安装,发现他桌面的图标还是老图标。卸载重新安装也没有用,这个问题一般是小米的机器才会发生。其实就是有缓存,怎么解决呢?下面提供两种方案:
1.进入目录 /data/system/customized_icons 下,找到你原来的旧图标,删除即可。需要root权限
2.把当前的工程换一个包名,重新安装即可。换了包名等于是一个新的应用。旧的缓存图标就失效了