#怎样把光标放在EditText中文本的末尾处
Editable etext = mSubjectTextEditor.getText();
Selection.setSelection(etext, etext.length());
#Int和byte数组之间的转换
有时候和C的程序通信的时候,我们在封装协议时,可能需要将Java里的int值,转换成byte[]后用socket发送。所以我们需要将32位的int值放到4字节的byte[]里。
/**
* int值转成4字节的byte数组
* @param num
* @return
*/
public static byte[] int2byteArray(int num) {
byte[] result = new byte[4];
result[0] = (byte)(num >>> 24);//取最高8位放到0下标
result[1] = (byte)(num >>> 16);//取次高8为放到1下标
result[2] = (byte)(num >>> 8); //取次低8位放到2下标
result[3] = (byte)(num ); //取最低8位放到3下标
return result;
}
反过来,将4字节的byte[]转成int值:
/**
* 将4字节的byte数组转成int值
* @param b
* @return
*/
public static int byteArray2int(byte[] b){
byte[] a = new byte[4];
int i = a.length - 1,j = b.length - 1;
for (; i >= 0 ; i--,j--) {//从b的尾部(即int值的低位)开始copy数据
if(j >= 0)
a[i] = b[j];
else
a[i] = 0;//如果b.length不足4,则将高位补0
}
int v0 = (a[0] & 0xff) << 24;//&0xff将byte值无差异转成int,避免Java自动类型提升后,会保留高位的符号位
int v1 = (a[1] & 0xff) << 16;
int v2 = (a[2] & 0xff) << 8;
int v3 = (a[3] & 0xff) ;
return v0 + v1 + v2 + v3;
}
#取消软键盘自动弹出
在实际操作过程中,edittext会自动获取焦点,导致软键盘自动弹出。虚拟机则不会,做如下修改
android:windowSoftInputMode="adjustUnspecified|stateHidden"
android:configChanges="orientation|keyboardHidden"
//切屏不会重新调用各个生命周期,只会执行onConfigurationChanged方法
windowSoftInputMod详解 configChanges详解
#获取方法名称
private static String getClassName() {
String result;
// 这里的数组的index2是根据你工具类的层级做不同的定义,这里仅仅是关键代码
StackTraceElement thisMethodStack = (new Exception()).getStackTrace()[2];
result = thisMethodStack.getClassName();
int lastIndex = result.lastIndexOf(".");
result = result.substring(lastIndex + 1, result.length());
return result;
}
/* * Drawable → Bitmap */
private static Bitmap drawable2Bitmap(Drawable drawable) {
if (drawable == null) {
return null;
}
// 取 drawable 的长宽
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
// 取 drawable 的颜色格式
Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888: Bitmap.Config.RGB_565;
// 建立对应 bitmap
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
// 建立对应 bitmap 的画布
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
// 把 drawable 内容画到画布中
drawable.draw(canvas);
return bitmap;
}