看别人博客,有些小技巧就直接转过来了,以后做开发可以大大提高开发效率。以下代码片摘自多个博客和自己平时的学习积累,若原作者认为侵犯著作权,请私信告知,我看到后将第一时间删除。

一、  获取系统版本号:

PackageInfo info = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
int versionCode=nfo.versionCode
string versionName=info.versionNam

二、获取系统信息:

String archiveFilePath="sdcard/download/Law.apk";//安装包路径
PackageManager pm = getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(archiveFilePath, PackageManager.GET_ACTIVITIES);
if(info != null){
ApplicationInfo appInfo = info.applicationInfo;
String appName = pm.getApplicationLabel(appInfo).toString();
String packageName = appInfo.packageName; //得到安装包名称
String version=info.versionName; //得到版本信息
Toast.makeText(test4.this, "packageName:"+packageName+";version:"+version, Toast.LENGTH_LONG).show();
Drawable icon = pm.getApplicationIcon(appInfo);//得到图标信息
TextView tv = (TextView)findViewById(R.id.tv); //显示图标
tv.setBackgroundDrawable(icon);

三、获取安装路径和已安装程序列表

android中获取当前程序路径
getApplicationContext().getFilesDir().getAbsolutePath()
(2)android取已安装的程序列表
List<PackageInfo> packageInfoList = getPackageManager().getInstalledPackages(0);

四、获取图片、应用名、包名

PackageManager pManager = MessageSendActivity.this.getPackageManager();
List<PackageInfo> appList = Utils.getAllApps(MessageSendActivity.this); for(int i=0;i<appList.size();i++) { PackageInfo pinfo = appList.get(i); ShareItemInfo shareItem = new ShareItemInfo(); //set Icon shareItem.setIcon(pManager.getApplicationIcon(pinfo.applicationInfo)); //set Application Name shareItem.setLabel(pManager.getApplicationLabel(pinfo.applicationInfo).toString()); //set Package Name shareItem.setPackageName(pinfo.applicationInfo.packageName);
}

五、解决listview上 Item上有按钮时 item本身不能点击的问题

1. 在item试图上面添加代码: android:descendantFocusability="blocksDescendants"
2.在listview里 添加代码 android:focusable="true"

六、不让文本框输入中文:

android:digits="1234567890qwertyuiopasdfghjklzxcvbnm`-=[]\;,./~!@#$%^*()_+}{:?&<>"'"
这样就不会输入中文了。

七、获取屏幕宽高

DisplayMetrics displayMetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;

八、将TabWidget显示在屏幕下方

设置TabWidget的属性 android:layout_alignParentBottom="true"

九、获取线程ID和线程名称:

Log.v("@@@@@@@@@@",Thread.currentThread().getId()+" "+Thread.currentThread().getName());

十、android中调用其它android应用

ComponentName comp = new ComponentName("com.Test","com.login.Main"); intent = new Intent(); intent.setComponent(comp); intent.setAction("android.intent.action.VIEW"); startActivity(intent);

十一、禁止软键盘弹出

EditText有焦点(focusable为true)阻止输入法弹出 editText.setInputType(InputType.TYPE_NULL); // 关闭软键盘 当EidtText无焦点(focusable=false)时阻止输入法弹出

InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);

【Android】EditText标签调用键盘
在xml文件中EditText标签有一个属性android:editable="false"和android:numeric="integer"

android:numeric="integer"表示只允许输入数字,此属性可以限制用户只能输入数字内容。
android:editable表示是否可以输入内容TRUE表示可以输入,false表示不允许输入内容;
当为android:editable="false"时,点击输入框,虚拟键盘是显示不出来的,不过当设置了 android:editable=""属性时,不管是false还是true,在其后加入android:numeric="integer"属性时,是可以输入数字内容了;这里没搞明白是怎么回事,也许是numeric把前面的属性覆盖掉了。
当android:editable="false"时,在java类里如果再规定EditText.setEnabled(true)时,虚拟键盘还是不会显示的。

十二、模拟器的各种规格与分辨率对照:

单位:像素
WVGA854: 854*480
WVGA800: 800*480
HVGA: 480*320
QVGA: 320*240
WQVGA432:432*240
WQVGA400:400*240 

十三、调用Android其他Context的Activity

Context c = createPackageContext("chroya.demo", Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
//载入这个类
Class clazz = c.getClassLoader().loadClass("chroya.demo.Main");
//新建一个实例
Object owner = clazz.newInstance();
//获取print方法,传入参数并执行
Object obj = clazz.getMethod("print", String.class).invoke(owner, "Hello");

这个方法有两个参数:
1、packageName  包名,要得到Context的包名
2、 flags  标志位,有CONTEXT_INCLUDE_CODE和CONTEXT_IGNORE_SECURITY两个选项。 CONTEXT_INCLUDE_CODE的意思是包括代码,也就是说可以执行这个包里面的代码。CONTEXT_IGNORE_SECURITY的意思 是忽略安全警告,如果不加这个标志的话,有些功能是用不了的,会出现安全警告。

十四、android4.0Dialog风格小技巧

4.0上如果还用Theme.Dialog,只能说很土,跟整体UI风格差别很大

请使用android:theme="@android:style/Theme.Holo.DialogWhenLarge"

十五、程序中安装apk(其中“apk”为你要安装的那个文件)

Intent intent = new Intent();           intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setAction(android.content.Intent.ACTION_VIEW);intent.setDataAndType(Uri.fromFile(“APK”),"application/vnd.android.package-archive");startActivity(intent);

十六、获取设备型号、SDK版本及系统版本

String device_model = Build.MODEL; // 设备型号
String version_sdk = Build.VERSION.SDK; // 设备SDK版本
String version_release = Build.VERSION.RELEASE; // 设备的系统版本  

十七、图片分析功能

public void SharePhoto(String photoUri,final Activity activity) {  Intent shareIntent = new Intent(Intent.ACTION_SEND);  File file = new File(photoUri);  shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));  shareIntent.setType("image/jpeg");  StartActivity(Intent.createChooser(shareIntent, activity.getTitle()));
}  

十八、linux关机命令(乱入一条

在Windows下,按着电源键4秒强制关机,在Linux下强烈不建议这么做。Windows由于是单用户、“假多”任务的情况,所以即使你的计算机关机,也不会对别人造成影响。不过在Linux中,由于每个程序都是在后台执行的,因此,在你看不到的屏幕背后可能有很多人同时在你的主机上工作。而且,若不正常关机可能会造成文件系统的损毁。所以,正常情况下,要关机时需要注意下面几件事情:

(1)查看系统的使用状态。

要看目前有谁在线,可以用who命令。要看网络的联机状态,可以用netstat-a命令。要看后台执行那个的程序可以执行ps-aux命令。

(2)通知在线用户的关机时刻

这个时候可以使用shutdown命令

Shutdown命令:
语法:shutdown[-t秒][-arkhncfF]时间 警告消息
-t:后面加描述表示过几秒之后关机。
-k:不是真的关机,仅仅发出警告消息。
-r:将系统服务停掉之后重启。
-h:将系统服务停掉之后立即关机。
-f:关机并开机之后,强制跳过fsck的磁盘检查。
-F:系统重启之后,强制进行fsck的磁盘检查。
-c:取消已经进行的shutdown命令内容。另外,重启关机命令有reboot、halt、poweroff。其实在默认情况下,都完成一样的工作。
halt先调用shutdown,而shutdown最后调用halt。不过,shutdown可以根据目前已经启动的服务来逐次关闭服务后才关机;而halt能够在不理会目前系统情况下,进行硬件关机的特殊功能。除了这些,还有一个关机命令是init 0
init是切换执行等级的命令。Linux共有7种执行等级,比较重要的是下面4种等级:
run level 0:关机
run level 3:纯命令行模式
run level 5:含有图形界面模式
run level 6:重启

十九、让自己的应用不被kill掉

可以在frameworks\base\services\java\com\android\server\am\ActivityManagerService.java这个类的forceStopPackage中加一个条件:

public void forceStopPackage(final String packageName) {if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)!= PackageManager.PERMISSION_GRANTED) {String msg = "Permission Denial: forceStopPackage() from pid="+ Binder.getCallingPid()+ ", uid=" + Binder.getCallingUid()+ " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;Slog.w(TAG, msg);throw new SecurityException(msg);}        long callingId = Binder.clearCallingIdentity();try {IPackageManager pm = ActivityThread.getPackageManager();int pkgUid = -1;synchronized(this) {try {pkgUid = pm.getPackageUid(packageName);} catch (RemoteException e) {}if (pkgUid == -1) {Slog.w(TAG, "Invalid packageName: " + packageName);return;}//begin:加入一个判断条件if (packageName.equals("你的进程名")) {return;}//end: 加入一个判断条件                                forceStopPackageLocked(packageName, pkgUid);}} finally {Binder.restoreCallingIdentity(callingId);}}

这样的话在任务管理器里可以保证KISS不掉的;
还有在这个方法上还有个方法clearApplicationUserData中保证如果是该进程就不让调用forceStopPackage()方法。

另:其他方法:
1,首先在你的service的onDestory方法里面写上启动你自己的代码,为什么要写这个?因为如果用户是在设置->应用程序->正在运行服务这里面杀掉你service的话会调用到onDestory方法的,这里就可以启动了,
2:监听屏幕关闭广播,屏幕已关闭,就启动服务。

3:监听屏幕解锁广播,一样的道理,这样,基本上,你的service就达到永不停止了。对用户来说有点变态,但很多软件都这样。

二十、EditText获取焦点:

EditText.requestFoucus()

二十一、获取手机屏幕分辨率

    DisplayMetrics  dm = new DisplayMereics();  getWindowManager().getDefaultDisplay().getMetrics(dm);  float width = dm.widthPixels * dm.density;  float height = dm.heightPixels * dm.density  

二十二、在Activity里面播放背景音乐

   public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.mainlay);  mediaPlayer = MediaPlayer.create(this, R.raw.mu);  mediaPlayer.setLooping(true);  mediaPlayer.start();  }  

二十三、让程序的界面不随机器的重力感应而翻转

第一种方法,在manifast文件里面

 <activity  android:screenOrientation="portrait">  </activity>  

第二种,在代码里面

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);  

二十四、使activity全屏显示

 requestWindowFeature(Window.FEATURE_NO_TITLE);  getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,WindowManager.LayoutParams. FLAG_FULLSCREEN);  

二十五、在RelativeLayout中使selector要注意点

关于selector的使用方法,可以参考http://blog.csdn.net/aomandeshangxiao/article/details/6759576这篇文章,今天,遇到在RelativeLayout中添加background为selector后没有反应的问题,寻摸了很长时间,一直没有找到原因,其实只要加上一句代码就完全可以解决:

RelativeLayout 里面加上android:clickable="true"

二十六、显示或隐藏虚拟键盘

    显示:  InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));  imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);  隐藏:  InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));  imm.hideSoftInputFromWindow(m_edit.getWindowToken(), 0);  

二十七、退出程序时清除通知中信息

  NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);  nm.cancelAll();  

二十八、创建快捷方式

    Intent intent=new Intent();  //设置快捷方式的图标  intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.img));  //设置快捷方法的名称  intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "点击启动哥的程序");            //设置点击快键图标的响应操作  
    intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(this,MainActivity.class));  //传递Intent对象给系统  setResult(RESULT_OK, intent);  finish();  

二十九、获取文件中的类名:

    String path = context.getPackageManager().getApplicationInfo(  context.getPackageName(), 0).sourceDir;  DexFile dexfile = new DexFile(path);  Enumeration<String> entries = dexfile.entries();  while (entries.hasMoreElements()) {  String name = (String) entries.nextElement();  ......  }  

三十. TextView中的getTextSize返回值是以像素(px)为单位的,

而setTextSize()是以sp为单位的.

所以如果直接用返回的值来设置会出错,解决办法是:

用setTextSize()的另外一种形式,可以指定单位

    TypedValue.COMPLEX_UNIT_PX : Pixels    TypedValue.COMPLEX_UNIT_SP : Scaled Pixels    TypedValue.COMPLEX_UNIT_DIP : Device Independent Pixels  

三十一. 在继承自View时,绘制bitmap时,需要将图片放到新建的drawable-xdpi

中,否则容易出现绘制大小发生改变

三十二. 在文字中加下划线: textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

三十三. scrollView是继承自frameLayout,所以在使用LayoutParams时需要用frameLayout的

三十四、android阴影字体设置

    <TextView  android:id="@+id/tvText1"   android:layout_width="wrap_content"   android:layout_height="wrap_content"   android:text="text1"   android:textSize="30sp"   android:textStyle="bold"   android:textColor="#FFFFFF"   android:shadowColor="#ff0000ff"  android:shadowDx="5"  android:shadowDy="5"       android:shadowRadius="10"/>  

android:shadowColor 阴影颜色

android:shadowDx 阴影的水平偏移量

android:shadowDy 阴影的垂直偏移量

android:shadowRadius 阴影的范围

为了统一风格和代码的复用,通常可以把这个样式抽取放入到style.xml文件中

    <?xml version="1.0" encoding="utf-8"?>  <resources>  <style name="textstyle">         <item name="android:shadowColor">#ff0000ff</item>  <item name="android:shadowRadius">10</item>  <item name="android:shadowDx">5</item>  <item name="android:shadowDy">5</item>       </style>  </resources>  
    <TextView  style="@style/textstyle"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:text="字体样式"  android:textSize="30sp"  android:textStyle="bold" />  

三十五、android实现手机震动功能(这个还可以创建一个数组来控制震动,达到震动几秒然后再震动几秒,,你懂得)

    import android.app.Activity;  import android.app.Service;  import android.os.Vibrator;  public class TipHelper {   public static void Vibrate(final Activity activity, long milliseconds) {  Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE);  vib.vibrate(milliseconds);  }  public static void Vibrate(final Activity activity, long[] pattern,boolean isRepeat) {  Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE);  vib.vibrate(pattern, isRepeat ? 1 : -1);  }  }  

还需要在AndroidManifest.xml 中添加震动权限:

    <uses-permission android:name="android.permission.VIBRATE" />  

通过上面操作,我们可以使用TipHelper所定义的函数了。两个Vibrate函数的参数简单介绍如下:

final Activity activity  :调用该方法的Activity实例

long milliseconds :震动的时长,单位是毫秒

long[] pattern    :自定义震动模式 。数组中数字的含义依次是[静止时长,震动时长,静止时长,震动时长。。。]时长的单位是毫秒

boolean isRepeat : 是否反复震动,如果是true,反复震动,如果是false,只震动一次

三十六、常用的正则表达式

^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$    //email地址 
       ^[a-zA-z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$  //url
       ^(d{2}|d{4})-((0([1-9]{1}))|(1[1|2]))-(([0-2]([1-9]{1}))|(3[0|1]))$ //年-月-日
       ^((0([1-9]{1}))|(1[1|2]))/(([0-2]([1-9]{1}))|(3[0|1]))/(d{2}|d{4})$  //月/日/年
       ^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$   //Emil
       ^((\+?[0-9]{2,4}\-[0-9]{3,4}\-)|([0-9]{3,4}\-))?([0-9]{7,8})(\-[0-9]+)?$     //电话号码
       ^(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5])$   //IP地址

(^\s*)|(\s*$)   // 首尾空格

^[a-zA-Z][a-zA-Z0-9_]{4,15}$  // 帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线)

^[1-9]*[1-9][0-9]*$  //  腾讯QQ号

三十七、输入框不挤压activity布局

在manifest的activity下添加

  1. android:windowSoftInputMode="adjustPan"

三十八、listview中item中button可点击:

    android:descendantFocusability="blocksDescendants"  

三十九、获取移动设备的IP地址:

    public class Tools {  public static String getLocalIpAddress() {    try {    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {    NetworkInterface intf = en.nextElement();    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {    InetAddress inetAddress = enumIpAddr.nextElement();    if (!inetAddress.isLoopbackAddress()) {    return inetAddress.getHostAddress().toString();    }    }    }    } catch (SocketException ex) {    Log.e("出错啦", ex.toString());    }    return null;    }    }  然后  WifiManager wm = (WifiManager)getSystemService(WIFI_SERVICE);  WifiInfo wi = wm.getConnectionInfo();  System.out.println("IP地址是:"+Tools.getLocalIpAddress());  System.out.println("SSID:"+wi.getSSID());  最后记得加两个权限  <uses-permission android:name="android.permission.INTERNET"/>  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>  

四十、高仿小米launcher跨屏拖动item(GridView长按item进行拖动

触发长按事件后浮动原理:

    windowParams = new WindowManager.LayoutParams();  windowParams.gravity = Gravity.TOP | Gravity.LEFT;  windowParams.x = x - itemWidth / 2;  windowParams.y = y - itemHeight / 2;  windowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;  windowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;  ImageView iv = new ImageView(getContext());  iv.setImageBitmap(bm);  windowManager = (WindowManager) getContext().getSystemService(  Context.WINDOW_SERVICE);// "window"  windowManager.addView(iv, windowParams);  

拖动效果:

    if (dragImageView != null) {  windowParams.alpha = 0.6f;  windowParams.x = x - itemWidth / 2;  windowParams.y = y - itemHeight / 2;  windowManager.updateViewLayout(dragImageView, windowParams);  }  

四十一、数据库写入图片信息:

数据库中的字段设置为 binary类型
Bitmap bitmap = BitmapFactory.decodeFile(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();bitmap.compress(CompressFormat.JPEG, 50, baos);
String sql = "insert into pic_info(pic_data, pic_name,pic_size,send_date,is_success) " +"values(?,?,?,?,?)";Object[] args = new Object[]{baos.toByteArray(), name, size, now, isSucess};
db.insert(sql, args);
读取数据库的图片信息:
byte[] picData = cursor.getBlob(cursor.getColumnIndex("pic_data"));
bitmap.setImageBitmap(BitmapFactory.decodeByteArray(picData, 0, picData.length));

四十二、listView的addView的问题。

在listView里使用addView()、addFooterView(v)、addHeaderView(v)时,要在setAdepter以前添加,或者在重写的Adapter中添加。因为setAdapter以后,就是listView已经绘制完毕,不能再进行添加。

四十三、progressBar修改颜色

有的时候,我们使用progressBar的时候,后面的背景色是白色或者是亮色,使得progressBar效果很不明显,所以,我们可以在下面三条中随意添加一条熟悉就可以了:

<ProgressBar style="@android:style/Widget.ProgressBar.Inverse"/>
<ProgressBar style="@android:style/Widget.ProgressBar.Large.Inverse"/>
<ProgressBar style="@android:style/Widget.ProgressBar.Small.Inverse"/>

四十四、窗口透明(背景模糊等)

先看下效果图:

第一种效果:

在styles.xml中定义

<style name="Theme.Translucent" parent="android:style/Theme.Translucent">
<item name="android:windowBackground">
@drawable/translucent_background
</item>
<item name="android:windowNoTitle">true</item>
<item name="android:colorForeground">#fff</item>
</style>

第二种效果是在源代码里面修改,在onCreate方法里面添加:

getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
setContentView(R.layout.translucent_background);

设置模糊效果是通过窗口管理器(WindowManager)设置参数来完成的,这种设置只有在背景设置为透明后才能显示效果。

四十五、Android输入框和文本框滚动条ScrollView

我们都知道EditText与TextView是Android的文本输入框和文本显示框,但是基于手机屏幕的大小因素,如果在需要输入较多文字或者显示较多内容的时候,手机屏幕是远远不够的,因此让文本框具有滚动条的功能是手机上必备的,要加上滚动条,其实很简单,只需要在文本输入框或者文本显示框上面加上滚动条控件即可,该控件名字为ScrollView,以下我们对比下(以TextView举例)。

<ScrollView
android:id="@+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="200px"
android:scrollbarStyle="outsideOverlay" android:background="@android:drawable/edit_text">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/textView"
/>
</ScrollView>

四十六、Android模拟器启动内存错误(内存不能为read)

如图

运行模拟器的时候总是会内存错误。

这种情况偶尔出现,没什么关系,不用管他。点击‘取消’就可以了。

经常出现就危险了,弄不好就得重装系统了。

运行某些程序的时候,有时会出现内存错误的提示,然后该程序就关闭。 
“0x????????”指令引用的“0x????????”内存。该内存不能为“read”。 
“0x????????”指令引用的“0x????????”内存,该内存不能为“written”。 
一般出现这个现象有方面的,一是硬件,即内存方面有问题,二是软件

开始 运行 输入:cmd 确定:

在DOS提示符下输入:

for %1 in (%windir%\system32\*.dll) do regsvr32.exe /s %1

等待3分钟,左右后,搞定了。(如果怕输错,就把这句话复制上去)。

四十七、通过路径获取媒体文件信息

通过路径获取媒体文件信息  http://blog.csdn.net/aomandeshangxiao/article/details/6600725

四十八、Java中有用的文件操作

java文件操作 http://blog.csdn.net/aomandeshangxiao/article/details/6597302

四十九、Android文件读写

Android文件的读写 http://blog.csdn.net/aomandeshangxiao/article/details/6589510

五十、    scaleType属性与ImagView中图片的显示的关系

五十一、  Notification的属性notification的各种属性:

http://blog.csdn.net/aomandeshangxiao/article/details/6608101

五十二、Android控件实现震动:

先在res下面新创建anim文件夹,在该文件夹中创建shake.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"android:duration="1000" android:fromYDelta="0" android:toYDelta="10"android:fromXDelta="0"android:toXDelta="10"android:interpolator="@anim/cycle_7" />

最后引用了cycle_7,再在该文件夹中创建cycle_7.xml文件

<?xml version="1.0" encoding="utf-8"?><cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android"android:cycles="10" />

在Java代码里面:

Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);findViewById(R.id.image).startAnimation(shake);

五十三、Android 页面切换动画效果

http://hi.baidu.com/fountainblog/blog/item/66cb9918b0220eaa4bedbc2e.html

五十四、Android2.2完全退出程序

http://www.eoeandroid.com/thread-62284-1-1.html

五十五、Android按下back键非退出隐藏到后台

public boolean onKeyDown(int keyCode, KeyEvent event) {  if (keyCode == KeyEvent.KEYCODE_BACK) {  Intent intent = new Intent(Intent.ACTION_MAIN);  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  intent.addCategory(Intent.CATEGORY_HOME);  startActivity(intent);  return true;  }  return super.onKeyDown(keyCode, event);
}  

五十六、在Android开发中使用Gallery实现多级联动

http://mobile.51cto.com/hot-230282.htm

五十七、获取view在屏幕中的位置:

int[] points = { 0, 0 };
view.getLocationInWindow(points);

这里用数组存储view的x和y坐标,point[0]是x坐标,point[1]是y坐标。

五十八、在图形中添加文字

@Overrideprotected synchronized void onDraw(Canvas canvas) {super.onDraw(canvas);Rect rect = new Rect();this.mPaint.getTextBounds(this.text, 0, this.text.length(), rect);int x = (getWidth() / 2) - rect.centerX();int y = (getHeight() / 2) - rect.centerY();canvas.drawText(this.text, x, y, this.mPaint);}

五十九、使用Vibrator实现手机震动

@Overridepublic boolean onTouchEvent(MotionEvent event) {if(event.getAction() == MotionEvent.ACTION_DOWN){vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);long[] pattern = {800, 40,400, 30}; // OFF/ON/OFF/ON...vibrator.vibrate(pattern, 2);//-1不重复,非-1为从pattern的指定下标开始重复}return super.onTouchEvent(event);} 

六十、界面重绘

invalidate()或者view.postinvalidate()方法

六十一、Android创建桌面快捷方式:

/** * 为程序创建桌面快捷方式 */
private void addShortcut(){  Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");  //快捷方式的名称  shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));  shortcut.putExtra("duplicate", false); //不允许重复创建  //指定当前的Activity为快捷方式启动的对象: 如 com.everest.video.VideoPlayer  //注意: ComponentName的第二个参数必须加上点号(.),否则快捷方式无法启动相应程序  ComponentName comp = new ComponentName(this.getPackageName(), "."+this.getLocalClassName());  shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));  //快捷方式的图标  ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);  shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);  sendBroadcast(shortcut);
}

需要声明权限

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" /> 

参考博客:

http://www.cnblogs.com/-OYK/archive/2011/05/31/2064797.html

http://www.apkbus.com/android-17389-1-1.html

http://dev.10086.cn/cmdn/wiki/index.php?edition-view-8836-1.html

六十二、android画图去锯齿效果

paint.setAntiAlias(true);

画图片的时候,前面设置没有用

canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTE

六十三、获取sd卡里文件信息

public class SDFileExplorer extends Activity{ListView listView;TextView textView;// 记录当前的父文件夹File currentParent;// 记录当前路径下的所有文件的文件数组File[] currentFiles;@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);//获取列出全部文件的ListViewlistView = (ListView) findViewById(R.id.list);textView = (TextView) findViewById(R.id.path);//获取系统的SD卡的目录File root = new File("/mnt/sdcard/");//如果 SD卡存在if (root.exists()){currentParent = root;currentFiles = root.listFiles();//使用当前目录下的全部文件、文件夹来填充ListViewinflateListView(currentFiles);}// 为ListView的列表项的单击事件绑定监听器listView.setOnItemClickListener(new OnItemClickListener(){@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id){// 用户单击了文件,直接返回,不做任何处理if (currentFiles[position].isFile())return;// 获取用户点击的文件夹下的所有文件File[] tmp = currentFiles[position].listFiles();if (tmp == null || tmp.length == 0){Toast.makeText(SDFileExplorer.this, "当前路径不可访问或该路径下没有文件",20000).show();}else{//获取用户单击的列表项对应的文件夹,设为当前的父文件夹currentParent = currentFiles[position];//保存当前的父文件夹内的全部文件和文件夹currentFiles = tmp;// 再次更新ListViewinflateListView(currentFiles);}}});// 获取上一级目录的按钮Button parent = (Button) findViewById(R.id.parent);parent.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View source){try{if (!currentParent.getCanonicalPath().equals("/mnt/sdcard")){// 获取上一级目录currentParent = currentParent.getParentFile();// 列出当前目录下所有文件currentFiles = currentParent.listFiles();// 再次更新ListViewinflateListView(currentFiles);}}catch (IOException e){e.printStackTrace();}}});}private void inflateListView(File[] files){// 创建一个List集合,List集合的元素是MapList<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();for (int i = 0; i < files.length; i++){Map<String, Object> listItem = new HashMap<String, Object>();//如果当前File是文件夹,使用folder图标;否则使用file图标if (files[i].isDirectory()){listItem.put("icon", R.drawable.folder);}else{listItem.put("icon", R.drawable.file);}listItem.put("fileName", files[i].getName());//添加List项listItems.add(listItem);}// 创建一个SimpleAdapterSimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems,R.layout.line, new String[] { "icon", "fileName" }, new int[] {R.id.icon, R.id.file_name });// 为ListView设置AdapterlistView.setAdapter(simpleAdapter);try{textView.setText("当前路径为:" + currentParent.getCanonicalPath());}catch (IOException e){e.printStackTrace();}}
}

六十四、Android标题栏显示progressBar

protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);//先给Activity注册界面进度条功能setContentView(R.layout.main);setProgressBarIndeterminateVisibility(true);//在需要显示进度条的时候调用这个方法setProgressBarIndeterminateVisibility(false);//在不需要显示进度条的时候调用这个方法
}

六十五、单击EditText全选内容

percent.setOnTouchListener(this);@Override
public boolean onTouch(View v, MotionEvent event) {
if(v.getId()==R.id.seekPercent) {
percent.selectAll();
InputMethodManager imm = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(v, 0);
return true;
}
return false;
}

六十六、Android设置图片圆角

/** * 将图片设置为圆角 */
public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect); final float roundPx = pixels; paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output;
}

六十七、把图片转换成圆形

bitmap = ((BitmapDrawable)imageView1.getDrawable()).getBitmap();
bitmap = getRoundedCornerBitmap(bitmap);
imageView1.setImageBitmap(bitmap);public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = bitmap.getWidth() / 2;paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
} 

六十八、TextView高级应用

1.    自定义字体

可以使用setTypeface(Typeface)方法来设置文本框内文本的字体,而android的 Typeface又使用TTF字体文件来设置字体

所以,我们可以在程序中放入TTF字体文件,在程序中使用Typeface来设置字体:第一步,在assets目录下新建fonts目录,把TTF字体文件放到这里。第二步,程序中调用:

TextViewtv = (TextView)findViewById(R.id.textView);

AssetManagermgr=getAssets();//得到AssetManager

Typefacetf=Typeface.createFromAsset(mgr, "fonts/mini.TTF");//根据路径得到Typeface

tv.setTypeface(tf);//设置字体

效果如下图所示:

2.    显示多种颜色的字

Android支持html格式的字符串,通过调用Html.fromHtml(str)方法可以转换html格式的字符串str。

示例如下:

StringtextStr1 = "<font color=\"#ffff00\">如果有一天,</font><br>";

StringtextStr2 = "<font color=\"#00ff00\">我厌倦了这里,</font><br>";

StringtextStr3 = "<font color=\"#ff00ff\">我会乘着梦,</font><br>";

StringtextStr4 = "<font color=\"#00ffff\">飞向那个属于自己的<br>世界……</font><br>";

tv.setText(Html.fromHtml(textStr1+textStr2+textStr3+textStr4));

运行后效果如下:

3.    字体加粗

在xml布局文件中使用android:textStyle=”bold”可以将英文设置成粗体,但是不能将中文设置成粗体,将中文设置成粗体的方法是:使用TextPaint的仿“粗体”设置setFakeBoldText为true。示例代码如下:

tv.getPaint().setFakeBoldText(true);

效果如下:

4.    添加阴影

在xml布局文件中使用一系列android:shadowXXX属性可添加设置阴影。具体为:shadowColor设置阴影颜色;shadowDx设置阴影水平偏移量;shadowDy设置阴影垂直偏移量;shadowRadius设置阴影半径。

示例代码:

android:shadowColor="#ffffff"

android:shadowDx="15.0"

android:shadowDy="5.0"

android:shadowRadius="2.5"

显示效果如下:

5.    插入图片

插入图片有两种方法,第一种方法就是用上面说的html格式的字符串,不过转换稍微有些麻烦。需要用到ImageGetter类来对图片的src属性进行转换。示例代码如下:

StringimgStr = "<img src=\""+R.drawable.sidai+"\"/>";

Html.ImageGetterimageGetter = new Html.ImageGetter() {

public Drawable getDrawable(Stringarg0) {

// TODO Auto-generated methodstub

int id =Integer.parseInt(arg0);

Drawable draw =getResources().getDrawable(id);

draw.setBounds(10, 10, 228,300);

return draw;

}

};

tv.append(Html.fromHtml(imgStr,imageGetter,null));

第二种方法是使用xml布局文件中一系列android:drawableXXX属性来实现插入图片。具体为:drawableBottom是在文本框内文本的底端绘制指定图像;drawableLeft是在文本框内文本的左边绘制指定图像;drawableRight是在文本框内文本的右边绘制指定图像;drawableTop是在文本框内文本的顶端绘制指定图像;drawablePadding设置文本框内文本与图像之间的间距。示例代码:

android:drawableBottom=”@drawable/sidai”

插入图片后的显示效果如下:

六十九、资源plurals表示数量的各种方式,

比如:一个教室有多少学生。考虑下面的例子:
there is 1 student;
there are 2 students;
there are 50 students;
显然对于2,50句子格式是一样的,对于1不同,Android支持将这种变体表示为plurals资源。

<pre name="code" class="html">    <?xml version="1.0" encoding="utf-8"?>  <resources>  <string name="hello">Hello World, Resource_Plurals!</string>  <string name="app_name">Resource_Plurals</string>  <plurals name="student">  <item quantity="one">There is 1 student</item>  <item quantity="other">There are %d  students</item>  </plurals>  </resources>  

在Java代码中获取定义的plurals资源

public class Resource_Plurals extends Activity {  /** Called when the activity is first created. */  @Override  public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.main);  Resources r = getResources();  String s1 = r.getQuantityString(R.plurals.student, 1,1);  Log.i("plurals", s1);  String s2 = r.getQuantityString(R.plurals.student, 2,2);  Log.i("plurals", s2);  String s3 = r.getQuantityString(R.plurals.student, 50,50);  Log.i("plurals", s3);  }
}  

七十、Android 自定义json解析类

<span style="font-size:18px;">import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
public final class JsonUtil{  /** * 把对象封装为JSON格式 * * @param o * 对象 * @return JSON格式 */  @SuppressWarnings("unchecked")  public static String toJson(final Object o){  if (o == null){  return "null";  }  if (o instanceof String) //String{  return string2Json((String) o);  }  if (o instanceof Boolean) //Boolean{  return boolean2Json((Boolean) o);
}
if (o instanceof Number) //Number{
return number2Json((Number) o);  }
if (o instanceof Map) //Map{
return map2Json((Map<String, Object>) o);  }
if (o instanceof Collection) //List Set{
return collection2Json((Collection) o);  }
if (o instanceof Object[]) //对象数组{
return array2Json((Object[]) o);  }
if (o instanceof int[])//基本类型数组
{  return intArray2Json((int[]) o);
}
if (o instanceof boolean[])//基本类型数组
{  return booleanArray2Json((boolean[]) o);
}
if (o instanceof long[])//基本类型数组
{  return longArray2Json((long[]) o);
}
if (o instanceof float[])//基本类型数组
{  return floatArray2Json((float[]) o);
}
if (o instanceof double[])//基本类型数组
{  return doubleArray2Json((double[]) o);
}
if (o instanceof short[])//基本类型数组
{  return shortArray2Json((short[]) o);
}
if (o instanceof byte[])//基本类型数组
{  return byteArray2Json((byte[]) o);
}
if (o instanceof Object) //保底收尾对象
{  return object2Json(o);
}
throw new RuntimeException("不支持的类型: " + o.getClass().getName());
}
/** * 将 String 对象编码为 JSON格式,只需处理好特殊字符 * * @param s * String 对象 * @return JSON格式 */
static String string2Json(final String s)
{  final StringBuilder sb = new StringBuilder(s.length() + 20);  sb.append('\"');  for (int i = 0; i < s.length(); i++)  {  final char c = s.charAt(i);  switch (c)  {  case '\"':  sb.append("\\\"");  break;  case '\\':  sb.append("\\\\");  break;  case '/':  sb.append("\\/");  break;  case '\b':  sb.append("\\b");  break;  case '\f':  sb.append("\\f");  break;  case '\n':  sb.append("\\n");  break;  case '\r':  sb.append("\\r");  break;  case '\t':  sb.append("\\t");  break;  default:  sb.append(c);  }  }  sb.append('\"');  return sb.toString();
}
/** * 将 Number 表示为 JSON格式 * * @param number * Number * @return JSON格式 */
static String number2Json(final Number number)
{  return number.toString();
}
/** * 将 Boolean 表示为 JSON格式 * * @param bool * Boolean * @return JSON格式 */
static String boolean2Json(final Boolean bool)
{  return bool.toString();
}
/** * 将 Collection 编码为 JSON 格式 (List,Set) * * @param c * @return */
static String collection2Json(final Collection<Object> c)
{  final Object[] arrObj = c.toArray();  return toJson(arrObj);
}
/** * 将 Map<String, Object> 编码为 JSON 格式 * * @param map * @return */
static String map2Json(final Map<String, Object> map)
{  if (map.isEmpty())  {  return "{}";  }  final StringBuilder sb = new StringBuilder(map.size() << 4); //4次方  sb.append('{');  final Set<String> keys = map.keySet();  for (final String key : keys)  {  final Object value = map.get(key);  sb.append('\"');  sb.append(key); //不能包含特殊字符  sb.append('\"');  sb.append(':');  sb.append(toJson(value)); //循环引用的对象会引发无限递归  sb.append(',');  }  // 将最后的 ',' 变为 '}':  sb.setCharAt(sb.length() - 1, '}');  return sb.toString();
}
/** * 将数组编码为 JSON 格式 * * @param array * 数组 * @return JSON 格式 */
static String array2Json(final Object[] array)
{  if (array.length == 0)  {  return "[]";  }  final StringBuilder sb = new StringBuilder(array.length << 4); //4次方  sb.append('[');  for (final Object o : array)  {  sb.append(toJson(o));  sb.append(',');  }  // 将最后添加的 ',' 变为 ']':  sb.setCharAt(sb.length() - 1, ']');  return sb.toString();
}
static String intArray2Json(final int[] array)
{  if (array.length == 0)  {  return "[]";  }  final StringBuilder sb = new StringBuilder(array.length << 4);  sb.append('[');  for (final int o : array)  {  sb.append(Integer.toString(o));  sb.append(',');  }  // set last ',' to ']':  sb.setCharAt(sb.length() - 1, ']');  return sb.toString();
}
static String longArray2Json(final long[] array)
{  if (array.length == 0)  {  return "[]";  }  final StringBuilder sb = new StringBuilder(array.length << 4);  sb.append('[');  for (final long o : array)  {  sb.append(Long.toString(o));  sb.append(',');  }  // set last ',' to ']':  sb.setCharAt(sb.length() - 1, ']');  return sb.toString();
}
static String booleanArray2Json(final boolean[] array)
{  if (array.length == 0)  {  return "[]";  }  final StringBuilder sb = new StringBuilder(array.length << 4);  sb.append('[');  for (final boolean o : array)  {  sb.append(Boolean.toString(o));  sb.append(',');  }  // set last ',' to ']':  sb.setCharAt(sb.length() - 1, ']');  return sb.toString();
}
static String floatArray2Json(final float[] array)
{  if (array.length == 0)  {  return "[]";  }  final StringBuilder sb = new StringBuilder(array.length << 4);  sb.append('[');  for (final float o : array)  {  sb.append(Float.toString(o));  sb.append(',');  }  // set last ',' to ']':  sb.setCharAt(sb.length() - 1, ']');  return sb.toString();
}
static String doubleArray2Json(final double[] array)
{  if (array.length == 0)  {  return "[]";  }  final StringBuilder sb = new StringBuilder(array.length << 4);  sb.append('[');  for (final double o : array)  {  sb.append(Double.toString(o));  sb.append(',');  }  // set last ',' to ']':  sb.setCharAt(sb.length() - 1, ']');  return sb.toString();
}
static String shortArray2Json(final short[] array)
{  if (array.length == 0)  {  return "[]";  }  final StringBuilder sb = new StringBuilder(array.length << 4);  sb.append('[');  for (final short o : array)  {  sb.append(Short.toString(o));  sb.append(',');  }  // set last ',' to ']':  sb.setCharAt(sb.length() - 1, ']');  return sb.toString();
}
static String byteArray2Json(final byte[] array)
{  if (array.length == 0)  {  return "[]";  }  final StringBuilder sb = new StringBuilder(array.length << 4);  sb.append('[');  for (final byte o : array)  {  sb.append(Byte.toString(o));  sb.append(',');  }  // set last ',' to ']':  sb.setCharAt(sb.length() - 1, ']');  return sb.toString();
}
public static String object2Json(final Object bean)
{  //数据检查  if (bean == null)  {  return "{}";  }  final Method[] methods = bean.getClass().getMethods(); //方法数组  final StringBuilder sb = new StringBuilder(methods.length << 4); //4次方  sb.append('{');  for (final Method method : methods)  {  try  {  final String name = method.getName();  String key = "";  if (name.startsWith("get"))  {  key = name.substring(3);  //防死循环  final String[] arrs =  { "Class" };  boolean bl = false;  for (final String s : arrs)  {  if (s.equals(key))  {  bl = true;  continue;  }  }  if (bl)  {  continue; //防死循环  }  }  else if (name.startsWith("is"))  {  key = name.substring(2);  }  if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0)  {  if (key.length() == 1)  {  key = key.toLowerCase();  }  else if (!Character.isUpperCase(key.charAt(1)))  {  key = key.substring(0, 1).toLowerCase() + key.substring(1);  }  final Object elementObj = method.invoke(bean);  //System.out.println("###" + key + ":" + elementObj.toString());  sb.append('\"');  sb.append(key); //不能包含特殊字符  sb.append('\"');  sb.append(':');  sb.append(toJson(elementObj)); //循环引用的对象会引发无限递归  sb.append(',');  }  }  catch (final Exception e)  {  //e.getMessage();  throw new RuntimeException("在将bean封装成JSON格式时异常:" + e.getMessage(), e);  }  }  if (sb.length() == 1)  {  return bean.toString();  }  else  {  sb.setCharAt(sb.length() - 1, '}');  return sb.toString();}
}
private JsonUtil(){
}
}  </span>

七十一、android自动跳转

有些时候需要类似这样的功能,在一个页面停留2秒后,跳转到另外一个页面!

第一种方法:

Timer timer = new Timer();TimerTask timerTask = new TimerTask() {@Overridepublic void run() {// 你要干的活}
};
timer.schedule(timerTask, 1000 * 2); //2秒后执行

在run()方法里面写上你的跳转就可以了。

第二种方法:

private final int SPLASH_DISPLAY_LENGHT = 2000;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  WindowManager.LayoutParams.FLAG_FULLSCREEN);  setContentView(R.layout.splash);new Handler().postDelayed(new Runnable() {@Overridepublic void run() {Intent intent = new Intent(Splash.this, XXX.class);Splash.this.startActivity(intent);overridePendingTransition(R.anim.fade_in, R.anim.fade_out);Splash.this.finish();}}, SPLASH_DISPLAY_LENGHT);}

使用handler延迟2秒后跳转。

七十二、Gally选中高亮状态

没有选中,在GalleryActivity中,设置gallery.setUnselectedAlpha(0.3f); 透明度为0.3 选中,在ImageAdapter的getView(int position, View convertView, ViewGroup parent)中,设置imageview.setBackgroundColor(Color.alpha(1)); 背景色为1

七十三、TextView颜色设置

android:textColor                    //设置文本颜色android:textColorHighlight           //被选中文字的底色,默认为蓝色android:textColorHint                //设置提示信息文字的颜色,默认为灰色。与hint一起使用。

七十四、Button使用Shape

<?xml version="1.0" encoding="utf-8"?>
<selectorxmlns:android="http://schemas.android.com/apk/res/android"><item android:state_pressed="true" ><shape><gradientandroid:startColor="#ff8c00"android:endColor="#FFFFFF"android:angle="270" /><strokeandroid:width="2dp"android:color="#dcdcdc" /><cornersandroid:radius="2dp" /><paddingandroid:left="10dp"android:top="10dp"android:right="10dp"android:bottom="10dp" /></shape></item>     <item android:state_focused="true" ><shape><gradientandroid:startColor="#ffc2b7"android:endColor="#ffc2b7"android:angle="270" /><strokeandroid:width="2dp"android:color="#dcdcdc" /><cornersandroid:radius="2dp" /><paddingandroid:left="10dp"android:top="10dp"android:right="10dp"android:bottom="10dp" /></shape></item>     <item>      <shape><gradientandroid:startColor="#ff9d77"android:endColor="#ff9d77"android:angle="270" /><strokeandroid:width="2dp"android:color="#fad3cf" /><cornersandroid:radius="2dp" /><paddingandroid:left="10dp"android:top="10dp"android:right="10dp"android:bottom="10dp" /></shape></item>
</selector>

七十五、Android Drawable叠加处理方法

大家可能知道Bitmap的叠加处理在Android平台中可以通过Canvas一层一层的画就行了,而Drawable中如何处理呢? 除了使用BitmapDrawable的getBitmap方法将Drawable转换为Bitmap外,今天Android123给大家说下好用简单的LayerDrawable类,LayerDrawable顾名思义就是层图形对象。下面直接用一个简单的代码表示:

   Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.cwj);Drawable[] array = new Drawable[3];      array[0] = new PaintDrawable(Color.BLACK); //黑色array[1] = new PaintDrawable(Color.WHITE); //白色array[2] = new BitmapDrawable(bm); //位图资源LayerDrawable ld = new LayerDrawable(array); //参数为上面的Drawable数组ld.setLayerInset(1, 1, 1, 1, 1);  //第一个参数1代表数组的第二个元素,为白色ld.setLayerInset(2, 2, 2, 2, 2); //第一个参数2代表数组的第三个元素,为位图资源mImageView.setImageDrawable(ld); 

上面的方法中LayerDrawable是关键,Android开发网提示setLayerInset方法原型为public void setLayerInset (int index, int l, int t, int r, int b) 其中第一个参数为层的索引号,后面的四个参数分别为left、top、right和bottom。对于简单的图片合成我们可以将第一和第二层的PaintDrawable换成BitmapDrawable即可实现简单的图片合成。

七十六、Android发信息时观察者

发信息大致的流程是:

观察者,ContentObserver

观察信息变化,它只能观察所有  就是 :Uri:content://sms/

你点击了发送按钮后,状态还是正在发送,这时这条信息已在你不注意时插入到发件箱中(调用 onChange一次,你可以查一下outbox的内容),当发送成功后(就会打发件箱的临时信息删除 又调用一次 onChange),成功后插入到已发信息sent(这是又会调用 onChange),它会调用三次,所以你们在观察发送信息时会出现onChange出现三次,这个解决方案我暂时只想到两种方案:

1:就是在contetnobserver类里定义一个变量 int count=0;@Overridepublic void onChange(boolean selfChange) {count++;//调用第三次才是已发信息if(count==3){//代表发送了一条信息Log.i("wet", "发送了一条信息");count=0;//以便第下次用}2:还有一个是:记录  context.getContentResolver().query(Uri.parse("content://sms/sent"), null, null, null, null);首先记录它上次的条数然后再记录它这次的条数,如果改变了,那就代表它改变了

七十七、Android屏幕解锁和点亮屏幕

最近在做一个闹钟的项目,当闹钟响起的时候需要用到自动解锁和点亮屏幕,因此记录一下解屏幕锁与点亮屏幕的代码:

KeyguardManager  km= (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); //得到键盘锁管理器对象
KeyguardLock kl = km.newKeyguardLock("unLock"); //参数是LogCat里用的Tagkl.disableKeyguard(); //解锁PowerManager pm=(PowerManager) getSystemService(Context.POWER_SERVICE);//获取电源管理器对象
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");
//获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
wl.acquire();//点亮屏幕
wl.release();//释放要实现自动解锁和点亮屏幕的功能则需要在AndroidManifest.xml添加权限:<uses-permission android:name="android.permission.WAKE_LOCK" /><uses-permission android:name="android.permission.DISABLE_KEYGUARD" />

七十八、去掉listView中间隔断线

方法1:listView.setDividerHeight(0);
方法2:this.getListView().setDivider(null);
方法3:android:divider="@null"android:cacheColorHint="#00000000" 设置其为透明!! 默认为黑色!!!!!

七十九、仿iphone的icon的效果

public static Bitmap toRoundCorner(Bitmap bitmap, int pixels)
{
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);return output;
} 

八十、android背景图圆角等处理

public static Bitmap toRoundCorner(Bitmap bitmap, int pixels)
{
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);return output;
} 

八十一、http连接

String  httpUrl = "www.baidu.com"; HttpClient httpClient = new DefaultHttpClient();HttpGet httpRequest = new HttpGet(httpUrl);try {HttpResponse httpResponse =httpClient.execute(httpRequest);if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){String strResult = EntityUtils.toString(httpResponse.getEntity());}} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}

post:

HttpClient httpClient = null
null;
HttpPost httpRequest = null
null;
HttpResponse httpResponse = null
null;
try {httpUrl = "http://192.168.1.7:8080/exa/index.jsp";// 取得默认的 HttpClienthttpClient = new DefaultHttpClient();// HttpPost 连接对象httpRequest = new HttpPost(httpUrl);// 使用 NameValuePair 来保存要传递的 Post 参数List<NameValuePair> params = new ArrayList<NameValuePair>();// 添加要传递的参数newparams.add(new BasicNameValuePair("testParam1", "110"));// 设置字符集HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");// 请求 httpRequesthttpRequest.setEntity(httpentity);// 取得 HttpResponsehttpResponse = httpClient.execute(httpRequest);// HttpStatus.SC_OK 表示连接成功if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 取得返回的字符串String strResult = EntityUtils.toString(httpResponse.getEntity());textView_1.setText(strResult);}
} catch (Exception e) {e.printStackTrace();
} finally {
}

八十二、

android里图片下载工具类AsyncImageLoader分析

八十三、

Android 实现 按钮从两边移到中间动画效果

八十四、实现listview 飞入效果

private LayoutAnimationController getListAnim() {AnimationSet set = new AnimationSet(true);Animation animation = new AlphaAnimation(0.0f, 1.0f);animation.setDuration(300);set.addAnimation(animation);animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,-1.0f, Animation.RELATIVE_TO_SELF, 0.0f);animation.setDuration(500);set.addAnimation(animation);LayoutAnimationController controller = new LayoutAnimationController(set, 0.5f);return controller;
}listView.setLayoutAnimation(getListAnim());

八十五、Gallery只滑动一张照片

    private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) {  return e2.getX() > e1.getX();  }  @Override  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {  // e1是按下的事件,e2是抬起的事件  int keyCode;  if (isScrollingLeft(e1, e2)) {  keyCode = KeyEvent.KEYCODE_DPAD_LEFT;  } else {  keyCode = KeyEvent.KEYCODE_DPAD_RIGHT;  }  onKeyDown(keyCode, null);  return true;  }  

八十六、活动解锁

http://www.eoeandroid.com/thread-175883-1-1.html

八十七、在TextView中自定义链接

如果只是简单需要textview在显示时候将网址、邮件地址、电话号码识别出来并且带上超链接,只需要在xml将textview的属性添加一个autoLink="all"即可。但是如果希望在文字中定义更复杂的超链接,比如:点击特定文字后跳转到某个activity,则需要自定义Html类对于tag的解析方法。整个处理流程思路如下:

  1. TextView的文字使用带html tag的字符串,如:<a href=\"http://www.diandian.com\">android</a>其实并不难;
  2. 为要做除了网址链接、邮件链接、电话链接之外的超链接自己确定一个tag名字,加入到字符串中,如:<a href=\"http://www.diandian.com\">android</a>其实并不难<mention>哪里哪里</mention>;
  3. 自定义一个静态类,并且实现TagHandler接口,以识别自定义的tag类型
public static class LinkHandler implements TagHandler{       private int startIndex = 0;          private int stopIndex = 0;private Context ctx;public LinkHandler(Context ctx){super();this.ctx=ctx;}//识别自定义标签的起始和终止位置public void handleTag(boolean opening, String tag, Editable output,XMLReader xmlReader) {if(tag.toLowerCase().equals(" mention")){if (opening) {  startTxt(tag, output, xmlReader);  } else {  endTxt(tag, output, xmlReader);  }}}public void startTxt(String tag, Editable output, XMLReader xmlReader) {  startIndex = output.length();  }  public void endTxt(String tag, Editable output, XMLReader xmlReader) {  stopIndex = output.length();  output.setSpan(new TagSpan(output.toString().substring(startIndex,stopIndex)), startIndex, stopIndex,  Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  }  //继承ClickableSpan类自定义类TagSpan实现OnClickListener接口,以此决定被识别出来的链接被点击后做什么private class TagSpan extends ClickableSpan implements OnClickListener {  String s;public TagSpan(String s){this.s=s;}@Override  public void onClick(View v) {  // 跳转某页面,将自定义tag对应的文字参数传递过去 NetActivity.pd.show();getUid(s);}}        }//在原始文本中提取@用户名 方式的文字出来,加上自定义的tag
public static String addTagsToString(String s){//对@添加tagPattern p=Pattern.compile("@[\\S&&[^@]]+");Matcher m=p.matcher(s);while(m.find()){s=s.replace(m.group(), "<mention>"+m.group()+"</mention>");}        s="<a>"+s+"</a>"; //此处一定要在前后加上一个<a>标签,否则@用户名之后若还有文字,会被一起加入到mention标签之中,这个问题还没搞清楚是为什么,至少目前加上<a>标签后不会有问题return s;}
  1. 然后在activity中为textview设定文字

tv.setText(Html.fromHtml(addTagsToString(s),null,new LinkHandler(ctx)));
tv.setMovementMethod(LinkMovementMethod.getInstance())

八十八、

模仿通讯录按字母分类显示,汉字,英文自动按英文字母分类显示,滑动时用气泡显示最上面的汉字首字母提示,右侧字母栏点击快速定位

八十九、listView Item里面存在Button

android:focusable="false"
android:clickable="false"
android:focusableInTouchMode="false"

九十、自定义progressBar样式

在XML文件中分别定义进度条背景、第一进度颜色、第二进度颜色,然后在ProgressBar的android:progressDrawable属性应用即可。
先在drawable下建立progressbar_style.xml文件,内容如下:

<span style="color:#009900;"><span style="color:#000000;"><strong><?xml</strong></span> <span style="color:#000066;">version</span>=<span style="color:#ff0000;">"1.0"</span> <span style="color:#000066;">encoding</span>=<span style="color:#ff0000;">"UTF-8"</span><span style="color:#000000;"><strong>?></strong></span></span>
<span style="color:#009900;"><span style="color:#000000;"><strong><layer-list</strong></span></span>
<span style="color:#009900;">  <span style="color:#000066;">xmlns:android</span>=<span style="color:#ff0000;">"http://schemas.android.com/apk/res/android"</span><span style="color:#000000;"><strong>></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong><item</strong></span> <span style="color:#000066;">android:id</span>=<span style="color:#ff0000;">"@android:id/background"</span><span style="color:#000000;"><strong>></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong><shape<span style="color:#000000;"><strong>></strong></span></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong><corners</strong></span> <span style="color:#000066;">android:radius</span>=<span style="color:#ff0000;">"5.0dip"</span> <span style="color:#000000;"><strong>/></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong><gradient</strong></span> <span style="color:#000066;">android:startColor</span>=<span style="color:#ff0000;">"#656666"</span> <span style="color:#000066;">android:endColor</span>=<span style="color:#ff0000;">"#dbdedf"</span> <span style="color:#000066;">android:angle</span>=<span style="color:#ff0000;">"270.0"</span> <span style="color:#000066;">android:centerY</span>=<span style="color:#ff0000;">"0.75"</span> <span style="color:#000066;">android:centerColor</span>=<span style="color:#ff0000;">"#bbbbbc"</span> <span style="color:#000000;"><strong>/></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong></shape<span style="color:#000000;"><strong>></strong></span></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong></item<span style="color:#000000;"><strong>></strong></span></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong><item</strong></span> <span style="color:#000066;">android:id</span>=<span style="color:#ff0000;">"@android:id/secondaryProgress"</span><span style="color:#000000;"><strong>></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong><clip<span style="color:#000000;"><strong>></strong></span></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong><shape<span style="color:#000000;"><strong>></strong></span></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong><corners</strong></span> <span style="color:#000066;">android:radius</span>=<span style="color:#ff0000;">"8.0dip"</span> <span style="color:#000000;"><strong>/></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong><gradient</strong></span> <span style="color:#000066;">android:startColor</span>=<span style="color:#ff0000;">"#e71a5e"</span> <span style="color:#000066;">android:endColor</span>=<span style="color:#ff0000;">"#6c213a"</span> <span style="color:#000066;">android:angle</span>=<span style="color:#ff0000;">"90.0"</span> <span style="color:#000066;">android:centerY</span>=<span style="color:#ff0000;">"0.75"</span> <span style="color:#000066;">android:centerColor</span>=<span style="color:#ff0000;">"#ac6079"</span> <span style="color:#000000;"><strong>/></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong></shape<span style="color:#000000;"><strong>></strong></span></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong></clip<span style="color:#000000;"><strong>></strong></span></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong></item<span style="color:#000000;"><strong>></strong></span></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong><item</strong></span> <span style="color:#000066;">android:id</span>=<span style="color:#ff0000;">"@android:id/progress"</span><span style="color:#000000;"><strong>></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong><clip<span style="color:#000000;"><strong>></strong></span></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong><shape<span style="color:#000000;"><strong>></strong></span></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong><corners</strong></span> <span style="color:#000066;">android:radius</span>=<span style="color:#ff0000;">"8.0dip"</span> <span style="color:#000000;"><strong>/></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong><gradient</strong></span> <span style="color:#000066;">android:startColor</span>=<span style="color:#ff0000;">"#464647"</span> <span style="color:#000066;">android:endColor</span>=<span style="color:#ff0000;">"#2d9ae7"</span> <span style="color:#000066;">android:angle</span>=<span style="color:#ff0000;">"270.0"</span> <span style="color:#000000;"><strong>/></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong></shape<span style="color:#000000;"><strong>></strong></span></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong></clip<span style="color:#000000;"><strong>></strong></span></strong></span></span><span style="color:#009900;"><span style="color:#000000;"><strong></item<span style="color:#000000;"><strong>></strong></span></strong></span></span>
<span style="color:#009900;"><span style="color:#000000;"><strong></layer-list<span style="color:#000000;"><strong>></strong></span></strong></span></span>

分别定义背景,第一进度颜色,第二进度颜色
gradient是渐变,前面已经说过,corners定义的是圆角
布局中:

<span style="color:#009900;"><span style="color:#000000;"><strong><ProgressBar</strong></span> <span style="color:#000066;">android:id</span>=<span style="color:#ff0000;">"@+id/progressBar1"</span> <span style="color:#000066;">android:layout_width</span>=<span style="color:#ff0000;">"fill_parent"</span> <span style="color:#000066;">android:layout_height</span>=<span style="color:#ff0000;">"wrap_content"</span></span>
<span style="color:#009900;"><span style="color:#000066;">style</span>=<span style="color:#ff0000;">"?android:attr/progressBarStyleHorizontal"</span> <span style="color:#000066;">android:progressDrawable</span>=<span style="color:#ff0000;">"@drawable/progressbar_style"</span></span>
<span style="color:#009900;"><span style="color:#000066;">android:progress</span>=<span style="color:#ff0000;">"50"</span> <span style="color:#000066;">android:max</span>=<span style="color:#ff0000;">"100"</span> <span style="color:#000066;">android:secondaryProgress</span>=<span style="color:#ff0000;">"70"</span></span>
<span style="color:#009900;"><span style="color:#000000;"><strong>></strong></span><span style="color:#000000;"><strong></ProgressBar<span style="color:#000000;"><strong>></strong></span></strong></span></span>

九十一、

android自定义ProgressBar(仿淘宝)的加载效果

九十二、

android仿微信的开门效果

九十三、Activity中ConfigChanges属性配置描述

“mcc” The IMSI mobile country code (MCC) has changed — that is, a SIM hasbeen detected and updated the MCC.移动国家号码,由三位数字组成,每个国家都有自己独立的MCC,可以识别手机用户所属国家。
“mnc“ The IMSI mobile network code (MNC) has changed — that is, a SIM hasbeen detected and updated the MNC.移动网号,在一个国家或者地区中,用于区分手机用户的服务商。
“locale“ The locale has changed — for example, the user has selected a new language that text should be displayed in.用户所在地区发生变化。
“touchscreen“ The touchscreen has changed. (This should never normally happen.)
“keyboard“ The keyboard type has changed — for example, the user has plugged in an external keyboard.键盘模式发生变化,例如:用户接入外部键盘输入。
“keyboardHidden“ The keyboard accessibility has changed — for example, the user has slid the keyboard out to expose it.用户打开手机硬件键盘
“navigation“ The navigation type has changed. (This should never normally happen.)
“orientation“ The screen orientation has changed — that is, the user has rotated the device.设备旋转,横向显示和竖向显示模式切换。
“fontScale“ The font scaling factor has changed — that is, the user has selected a new global font size.全局字体大小缩放发生改变 

"screenSize"   The current available screen size has changed. This represents a change in the currently available size, relative to the current aspect ratio, so will change when the user switches between landscape and portrait. However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device).
Added in API level 13.

当前可用的屏幕尺寸发生改变。这代表了一个改变目前可用大小,相对于当前的长宽比例,当用户横竖屏切换时会发生改变。然而,如果您的应用程序的API级别是12或更低,那么你的Activity会自己处理这个配置变化(在Android 3.2或更高的版本,这个配置更改不会重启你的activity)。

九十四、

android ---- ImageUtil工具类

九十五、判断wifi是否打开:

public boolean isWiFiActive() {      ConnectivityManager connectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);      if (connectivity != null) {      NetworkInfo[] infos = connectivity.getAllNetworkInfo();      if (infos != null) {      for(NetworkInfo ni : infos){  if(ni.getTypeName().equals("WIFI") && ni.isConnected()){  return true;  }  }  }      }      return false;      }
// .........
}  
private boolean checkWifi() {  boolean isWifiConnect = true;  ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
[java] view plaincopyprint?
//check the networkInfos numbers
NetworkInfo[] networkInfos = cm.getAllNetworkInfo();
for (int i = 0; i<networkInfos.length; i++) {  if (networkInfos[i].getState() == NetworkInfo.State.CONNECTED) {  if(networkInfos[i].getType() == cm.TYPE_MOBILE) {  isWifiConnect = false;  }  if(networkInfos[i].getType() == cm.TYPE_WIFI) {  isWifiConnect = true;  }  }
}
return isWifiConnect;

九十六、java.util.MissingFormatArgumentException 错误

在有站位符的打印语句中,经常会犯下一个错误。

如:System.out.printf( "y=%3d "+y),就会报这个错误。

应修改为:;改为System.out.printf( "y=%3d ",y)

九十七、Android判断是Pad或者手机

public boolean isTabletDevice() {TelephonyManager telephony = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);int type = telephony.getPhoneType();if (type == TelephonyManager.PHONE_TYPE_NONE) {return true;} else {return false;}}

九十八、判断android网络状态

State mWifiState = null;State mMobileState = null;ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);mWifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();mMobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();if (mWifiState != null && mMobileState != null && State.CONNECTED != mWifiState&& State.CONNECTED == mMobileState) {// 手机网络连接成功} else if (mWifiState != null && mMobileState != null && State.CONNECTED != mWifiState && State.CONNECTED != mMobileState) {mHandler.sendEmptyMessage(MSG_SHOW_NET_DIALOG);} else if (mWifiState != null && State.CONNECTED == mWifiState) {// 无线网络连接成功}

九十九、ImageView的ScaleType属性

ImageView.ScaleType|android:scaleType值的意义:

ImageView.ScaleType.CENTER|android:scaleType="center" 按图片的原来size居中显示,当图片长/宽超过View的长/宽,则截取图片的居中部分显示

ImageView.ScaleType.CENTER_CROP|android:scaleType="centerCrop"按比例扩大图片的size居中显示,使得图片长 (宽)等于或大于View的长(宽)

ImageView.ScaleType.CENTER_INSIDE|android:scaleType="centerInside"将图片的内容完整居中显示,通过按比例缩小或原来的size使得图片长(宽)等于或小于View的长(宽)

ImageView.ScaleType.FIT_CENTER|android:scaleType="fitCenter"把图片按比例扩大(缩小)到View的宽度,居中显示

ImageView.ScaleType.FIT_END|android:scaleType="fitEnd"把图片按比例扩大(缩小)到View的宽度,显示在View的下部分位置

ImageView.ScaleType.FIT_START|android:scaleType="fitStart"把图片按比例扩大(缩小)到View的宽度,显示在View的上部分位置

ImageView.ScaleType.FIT_XY|android:scaleType="fitXY"把图片按照指定的大小在View中显示

ImageView.ScaleType.MATRIX|android:scaleType="matrix"用matrix来绘制

一百、垂直进度条

    @Override  protected synchronized void onDraw(Canvas canvas)  {  // TODO Auto-generated method stub  canvas.rotate(-90);//反转90度,将水平ProgressBar竖起来  canvas.translate(-getHeight(), 0);//将经过旋转后得到的VerticalProgressBar移到正确的位置,注意经旋转<span style="white-space:pre">                     </span>    后宽高值互换  super.onDraw(canvas);  }

一零一、android获取本机Ip地址

public String getLocalIpAddress() {  try {  for (Enumeration<NetworkInterface> en = NetworkInterface  .getNetworkInterfaces(); en.hasMoreElements();) {  NetworkInterface intf = en.nextElement();  for (Enumeration<InetAddress> enumIpAddr = intf  .getInetAddresses(); enumIpAddr.hasMoreElements();) {  InetAddress inetAddress = enumIpAddr.nextElement();  if (!inetAddress.isLoopbackAddress()) {  return inetAddress.getHostAddress().toString();  }  }  }  } catch (SocketException ex) {  Log.e("WifiPreference IpAddress", ex.toString());  }  return null;  }  

别忘了加权限:

  1. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
  2. <uses-permission android:name="android.permission.INTERNET"></uses-permission>

有时候,有的手机会有ip6地址,所以在if()判断里面,最好这样写:

[java] view plaincopy
  1. if (!inetAddress.isLoopbackAddress()&& InetAddressUtils
  2. .isIPv4Address(inetAddress
  3. .getHostAddress().toString())) {

一零二、开机启动

原理就是启动一个BroadcastReceiver来监听系统发出的开机广播:Android.intent.action.BOOT_COMPLETED

public class StartupReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stub//xxx 你要跳转到的activity       Intent i = new Intent(context,xxx.class);i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//将intent以startActivity传送给操作系统context.startActivity(i);}}

后面 在manifest里面注册BroadcastReceiver

<receiver android:name=".StartupReceiver">  <intent-filter>  <action android:name="android.intent.action.BOOT_COMPLETED" />  <category android:name="android.intent.category.HOME" />  </intent-filter>  </receiver> 

最后,再添加上权限就可以了

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>

一零三、Java对象赋值注意点

刚刚再看Think in Java 4的时候,提醒下自己!

对主数据类型的赋值是非常直接的。由于主类型容纳了实际的值,而且并非指向一个对象的句柄,所以在为其赋值的时候,可将来自一个地方的内容复制到另一个地方。例如,假设为主类型使用“A=B”,那么B处的内容就复制到A。若接着又修改了 A,那么 B 根本不会受这种修改的影响。作为一名程序员,这应成为自己的常识。 
       但在为对象“赋值”的时候,情况却发生了变化。对一个对象进行操作时,我们真正操作的是它的句柄。所以倘若“从一个对象到另一个对象”赋值,实际就是将句柄从一个地方复制到另一个地方。这意味着假若为对象使用“C=D”,那么C 和D最终都会指向最初只有 D 才指向的那个对象。下面这个例子将向大家阐示这一点。

把书中的例子稍微修改了下:

package cn.demo;
class Number { int i;
} public class Assignment { public static void main(String[] args) { Number n1 = new Number(); Number n2 = new Number(); n1.i = 9; n2.i = 47; System.out.println("1: n1.i: " + n1.i + ", n2.i: " + n2.i); n1.i = n2.i;System.out.println("2: n1.i: " + n1.i + ", n2.i: " + n2.i); n1.i = 32;System.out.println("3: n1.i: " + n1.i + ", n2.i: " + n2.i); n1 = n2; System.out.println("4: n1.i: " + n1.i + ", n2.i: " + n2.i); n1.i = 27; System.out.println("5: n1.i: " + n1.i + ", n2.i: " + n2.i); }
}

打印结果:

1: n1.i: 9, n2.i: 47
2: n1.i: 47, n2.i: 47
3: n1.i: 32, n2.i: 47
4: n1.i: 47, n2.i: 47
5: n1.i: 27, n2.i: 27

一零四、Notification点击取消

notification.flags |= Notification.FLAG_AUTO_CANCEL;

一零五、保留表结构,删除表中所有内容

"DELETE FROM " + TABLE_NAME + " WHERE 1 = 1"

一零六、Android手机获取手机唯一识别号

在开发手机应用时,开发者最关心的是开发的手机软件有多少用户安装,并且正在使用。这就需要识别手机的唯一性。目前我了解的有两种方法,获取手机的imei号(imei号是唯一识别手机的号码)。获取android id号(android id 是手机系统的唯一号码)。

  第一种方法:

  android获取手机imei号的方法在在android系统中获取imei号和其他手机信息一文中做了详细的介绍。其中android在 2.0以上的版本中,获取手机imei号已经不需要相应的读取手机信息的权限了。

  < uses-permission android:name="android.permission.READ_PHONE_STATE" />

  但是目前1.6以下的版本用户占用户的近50%,如果想要让1.6以下版本的用户也可以获取imei号,那就要添加权限。

  好处是唯一标识手机,缺点是可能需要相应的用户权限。

String myIMSI = android.os.SystemProperties.get(android.telephony.TelephonyProperties.PROPERTY_IMSI);

String myIMEI = android.os.SystemProperties.get(android.telephony.TelephonyProperties.PROPERTY_IMEI);

  第二种方法:

  可以获取android id号,如果一个手机设备第一次启动随即产生的一个数字,如果系统改变,该号可能会改变。

  android id号解释:http://androidappdocs-staging.appspot.com/reference/android /provider/Settings.Secure.html#ANDROID_ID

  获取方法:

  String t=android.provider.Settings.System.getString(getContentResolver(), "android_id");

  Log.i("huilurry","android_id="+t);

  Ms测试结果:

  07-13 13:12:49.835: INFO/huilurry(17455): android_id=20014289e714f20c

  好处是所有版本都试用,缺点是可能会和其他机子重复或本机改变。via:http://wangjun.easymorse.com /?p=665

3、获取IMEI是把,telephonypackage的TelephonyManager类的getDeviceId() 方法

获得IMSI / IMEI(SIM和手机的唯一识别ID)

  学习内容: 你将学到如何读出你手机里的SIM卡的IMSI (国际移动用户ID) 和IMEI (国际移动设备ID). IMSI 与 SIM唯一对应, IMEI 与 设备唯一对应.

  可能应用的场合: 你可能需要 唯一的id 去授权/注册,或者用于你的Android-Activity的license目的 下面的两行代码将会使你获得SIM卡唯一 ID IMSI 和设备唯一ID IMEI

  描述:
  IMSI是一个 唯一的数字, 标识了GSM和UMTS 网络里的唯一一个用户. 它 存储 在手机的SIM卡里,它会通过手机发送到网络上.

  IMEI也是一串唯一的数字, 标识了 GSM 和 UMTS网络里的唯一一个手机. 它通常被打印在手机里电池下面的那一面,拨  *#06# 也能看到它.

  代码: 这里是你在Android里读出 唯一的 IMSI-ID / IMEI-ID 的方法。
Java: 
         String myIMSI = android.os.SystemProperties.get(android.telephony.TelephonyProperties.PROPERTY_IMSI);

String myIMEI = android.os.SystemProperties.get(android.telephony.TelephonyProperties.PROPERTY_IMEI);

一零七、 静默卸载系统软件和第三方软件

一个个卸载软件,弹出卸载软件提示好麻烦,现在特作出下列方法,可以静默卸载静默安装敬请期待。。。。//下面3句是静默卸载系统软件命令String busybox="mount -o remount rw /system";String chmod="chmod 777 /system/app/HtcTwitter.apk";uninstallapk="rm -r /system/app/HtcTwitter.apk";//下面3句是静默卸载第三方软件命令String busybox1="mount -o remount rw /data";String chmod1="chmod 777 /data/app/com.yingyonghui.market-2.apk";uninstallapk1="pm uninstall com.yingyonghui.market";chmodApk(busybox1,chmod1);/** 对要卸载的apk赋予权限*/public void chmodApk(String busybox ,String chmod){try {Process process = null;DataOutputStream os = null;process = Runtime.getRuntime().exec("su");os = new DataOutputStream(process.getOutputStream());os.writeBytes(busybox);os.flush();os.writeBytes(chmod);os.flush();os.close();} catch (Exception ex) {ex.printStackTrace();}}/** 卸载apk*/public void uninstallApk(String uninstallapk){try {Process process = null;DataOutputStream os = null;process = Runtime.getRuntime().exec("su");os = new DataOutputStream(process.getOutputStream());os.writeBytes(uninstallapk);os.flush();os.close();} catch (Exception ex) {ex.printStackTrace();}}

一零八、

获取当前显示的activity

用ActivityManager里面可以获取到当前运行的所有任务,所有进程和所有服务,这是任务管理器的核心。仔细看getRunningTasks的文档,里面说获取的是系统中"running"的所有task,"running"状态包括已经被系统冻结的task。而且返回的这个列表是按照顺序排列的,也就是说第一个肯定比第二个后运行。

getRunningTasks有个整型参数,表示返回列表的最大个数。那么,我们如果把1作为参数给进去,那么他返回的task就是

ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
Log.d("", "pkg:"+cn.getPackageName());
Log.d("", "cls:"+cn.getClassName());

一零九、android代码实现ViewPager的indictor效果

一一零、Android 手绘 - 支持保存为图片

一一一、android 遮罩层效果

一一二、 Android中从SD卡中/拍照选择图片并进行剪裁的方法

一一三、android 复制功能实现

/*** 实现文本复制功能* @param content 要复制的内容*/
public static void copy(String content, Context context) {
// 得到剪贴板管理器
ClipboardManager cmb = (ClipboardManager) context
.getSystemService(Context.CLIPBOARD_SERVICE);
cmb.setText(content.trim());
}

一一四、 给图片加水印

try {ImageView img=(ImageView) findViewById(R.id.test_img_file);//获取从本地获取的文件路径,用FileInputstream读入文件,并将图片文件转换成位图Bundle bundle=getIntent().getExtras();String path=bundle.getString("test");FileInputStream fa=new FileInputStream(path);Bitmap bm=BitmapFactory.decodeStream(fa);//原图Bitmap wm=BitmapFactory.decodeResource(getResources(), R.drawable.wate_market);//水印//将creatBitmap()方法的返回值(返回位图)放到图片控件显示img.setImageBitmap(createBitMap(bm,wm));
} catch (IOException e) {e.printStackTrace();
}
}
});
}
private Bitmap createBitMap(Bitmap src,Bitmap wmsrc){/*** 水印制作方法*/String tag="xx";Log.d(tag, "开始了,画图");if(src==null){return null;}int w=src.getWidth();int h=src.getHeight();int wmw=wmsrc.getWidth();int wmh=wmsrc.getHeight();//create the new bitmapBitmap newb=Bitmap.createBitmap(w,h,Config.ARGB_8888);//创建一个底图Canvas cv=new Canvas(newb);//将底图画进去cv.drawBitmap(src, 0, 0,null);//在0,0坐标开始画入src//讲水印画进去cv.drawBitmap(wmsrc, w-wmw+5, h-wmh+5, null);//保存图片cv.save(Canvas.ALL_SAVE_FLAG);cv.restore();return newb;}
}
一一五、DialogFragment设置透明
在onCreatview里面加上:
getDialog().getWindow().setBackgroundDrawable(newColorDrawable(Color.TRANSPARENT));

安卓惯用实用功能代码片相关推荐

  1. 安卓常用实用功能代码片大全(长期更新)

    ↑duang!电脑浏览上面的'目录+'点击蓝字有惊喜 看别人博客,有些小技巧就直接转过来了,以后做开发可以大大提高开发效率.以下代码片摘自多个博客和自己平时的学习积累,若原作者认为侵犯著作权,请私信告 ...

  2. JavaScript实用功能代码片段

    JavaScript实用功能代码片段 1.原生JavaScript实现字符串长度截取1 function cutstr(str, len) {2 var temp;3 var icount = 0;4 ...

  3. 100个直接可以拿来用的JavaScript实用功能代码片段(转)

    把平时网站上常用的一些实用功能代码片段通通收集起来,方面网友们学习使用,利用好的话可以加快网友们的开发速度,提高工作效率. 目录如下: 1.原生JavaScript实现字符串长度截取 2.原生Java ...

  4. 100个原生的JavaScript实用功能代码片段

    把平时网站上常用的一些实用功能代码片段通通收集起来,方面网友们学习使用,利用好的话可以加快网友们的开发速度,提高工作效率. 目录如下: 1.原生JavaScript实现字符串长度截取 2.原生Java ...

  5. 1 5 php,直接可以拿来用的PHP惯用功能代码片段(1~5)

    文章来源:jquery教程 - http://www.jq-school.com/Show.aspx?id=322 前面已经分享了100个常用的原生JavaScript代码片段,现在有空就开始收集PH ...

  6. android系统代码行数,鸿蒙用460万行的代码量,实现安卓1525万行代码实现的所有功能...

    鸿蒙即将开源,目前最新的是OpenHarmony1.1,即将到来的是OpenHarmony,有很多同学对OpenHarmony的各个版本,以及L0到L5不太了解,现在就详细解释下.OpenHarmon ...

  7. 安卓视频播放器 一行代码快速实现视频播放,Android视频播放,AndroidMP3播放,安卓视频播放一行代码搞定,仿今日头条 Android视频播放器

    一行代码快速实现视频播放,Android视频播放,AndroidMP3播放,安卓视频播放一行代码搞定,真正实现Android的全屏功能 github地址:https://github.com/qius ...

  8. React Native系列(6) - 编译安卓私有React-Native代码

    为何要自己编译React Native安卓私有代码 我们在开发中遇到一个HTTP2的问题,React Native安卓客户端在和HTTP2支持的服务器通讯的过程中会有crash,见 React-Nat ...

  9. 安卓添加滚轮代码_iPhone为什么都不会中病毒?安卓默默退出群聊

    用Window电脑的小伙伴,或多或少都会安装一个360或者金山等杀毒防护软件,因为在互联网有很多恶意的软件,因此需要好好保护! 时代似乎正在改变,手机成为人手必备的产品,如今,网络犯罪分子越来越多地将 ...

最新文章

  1. 4.1 ucGUI 图片显示方法
  2. [置顶] 单例模式lua实现
  3. 这几道Redis面试题都不懂,怎么拿offer?
  4. 写程序时,经常要重载OnPaint,定位很麻烦,现在有个简单办法
  5. if or函数套用_IF函数和OR函数的套用我想利用IF函数和 – 手机爱问
  6. postfix 过滤中文内容
  7. Android NDK JNI C++ 3
  8. Python+FFmpeg提取哔哩哔哩安卓缓存
  9. PotPlayer没有声音解决方案
  10. 2019年图灵奖Edwin E. Catmull和Patrick M. Hanrahan简介
  11. 翻译: 2.7. 如何利用帮助文档 深入神经网络 pytorch
  12. Hadoop生态之Mapreduce
  13. css背景图铺满整个屏幕
  14. vue动态生成二维码,扫码登录
  15. box2d 碰撞检测_Box2d新系列 第四章 碰撞模块
  16. codeforces EDU suffix array
  17. C# .NET实现手机接收短信
  18. echarts扇形图
  19. 雅虎、百度、谷歌三大巨头比拼社区化搜索
  20. 科研论文课程幕课习题(第一二章)

热门文章

  1. 2018年研究生入学考试高等数学卷一
  2. 论Python的先进性!!!
  3. 80道漫画图解算法题汇总(0406版本)
  4. 一种比较同一情况下接收机工作特性曲线下面积的方法
  5. ABT 链节点五步速成法 | ArcBlock 博客
  6. Delphi7 中TStringList的Delimiter DelimitedText有BUG,字符串分割有问题
  7. JSPatch Convertor 实现原理详解 1
  8. 王者荣耀手风琴效果实现
  9. 教程 | 10分钟入门简笔画(彩色小插画)
  10. 强推集成GPT-4的编辑器Cursor;面向ChatGPT编程18种方法;如何将AI绘画融合于工作流;ChatGPT SEO公式大揭秘 | ShowMeAI日报