更新于2014-04-09
35. 如果ViewPager显示不出来看是不是没有设置高度,因为对于ViewPager来说,设置成wrap_content是不行的.要么是match_parent要么呢,指定具体的高度.
更新于2013-08-27
34. include进来的布局layout_margin不起作用。
解决方法需要同时设置layout_width和layout_height
see:http://stackoverflow.com/questions/11947987/margin-does-not-impact-in-include
最后更新:2012-08-15
33.设置EditText的inputType为优先使用数字键。
比如密码框,有些场景是使用纯数字的比较多,但是密码还是可以使用其它符号的。所以限定inputType为number的话肯定不行。为text就跟没有设置一样。所以。可以使用如下设置来解决这个问题:
passwordView.setRawInputType(Configuration.KEYBOARD_QWERTY);
更新:2012-06-06:
32.在EditText中将光标放在文本后面。参考
EditText et = (EditText)findViewById(R.id.inbox); et.setSelection(et.getText().length());
http://stackoverflow.com/questions/6217378/place-cursor-at-the-end-of-text-in-edittext
最后更新:2012-05-19:
31.使用android和浮点工具类而不是java.lang.Math的
Use android.util.FloatMath#ceil() instead of java.lang.Math#ceil to avoid argument float to double conversion Issue: Suggests replacing java.lang.Math calls with android.util.FloatMath to avoid conversions Id: FloatMath On modern hardware, "double" is just as fast as "float" though of course it takes more memory. However, if you are using floats and you need to compute the sine, cosine or square root, then it is better to use the android.util.FloatMath class instead of java.lang.Math since you can call methods written to operate on floats, so you avoid conversions back and forth to double. http://developer.android.com/guide/practices/design/performance.html#avoidfloat
30.android开发工具居然还能检测,你同样资源的重要啊,哈哈.
The following unrelated icon files have identical contents: btn_default_focused_holo_dark.9.png, btn_default_focused_holo_light.9.png Issue: Finds duplicated icons under different names Id: IconDuplicates If an icon is repeated under different names, you can consolidate and just use one of the icons and delete the others to make your application smaller. However, duplicated icons usually are not intentional and can sometimes point to icons that were accidentally overwritten or accidentally not updated.
29.检查无用的资源:
The resource R.drawable.add_fastlink_bg appears to be unused Issue: Looks for unused resources Id: UnusedResources Unused resources make applications larger and slow down builds.
28.使用新的prograud配置方案.
Local ProGuard configuration contains general Android configuration: Inherit these settings instead? Modify project.properties to define proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard.cfg and then keep only project-specific configuration here Issue: Checks for old proguard.cfg files that contain generic Android rules Id: ProguardSplit Earlier versions of the Android tools bundled a single "proguard.cfg" file containing a ProGuard configuration file suitable for Android shrinking and obfuscation. However, that version was copied into new projects, which means that it does not continue to get updated as we improve the default ProGuard rules for Android. In the new version of the tools, we have split the ProGuard configuration into two halves: * A simple configuration file containing only project-specific flags, in your project * A generic configuration file containing the recommended set of ProGuard options for Android projects. This generic file lives in the SDK install directory which means that it gets updated along with the tools. In order for this to work, the proguard.config property in the project.properties file now refers to a path, so you can reference both the generic file as well as your own (and any additional files too). To migrate your project to the new setup, create a new proguard-project.txt file in your project containing any project specific ProGuard flags as well as any customizations you have made, then update your project.properties file to contain: proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
27.关于使用设备独立的图片:
The image table_getcheck.png varies significantly in its density-independent (dip) size across the various density versions: drawable-hdpi\table_getcheck.png: 65x60 dp (97x90 px), drawable-mdpi\table_getcheck.png: 48x45 dp (48x45 px) Issue: Ensures that icons across densities provide roughly the same density-independent size Id: IconDipSize Checks the all icons which are provided in multiple densities, all compute to roughly the same density-independent pixel (dip) size. This catches errors where images are either placed in the wrong folder, or icons are changed to new sizes but some folders are forgotten.
26.使用SparseIntArray来提升性能,而不是使用HashMap<Integer,Integer>
Use new SparseIntArray(...) instead for better performance Issue: Looks for opportunities to replace HashMaps with the more efficient SparseArray Id: UseSparseArrays For maps where the keys are of type integer, it's typically more efficient to use the Android SparseArray API. This check identifies scenarios where you might want to consider using SparseArray instead of HashMap for better performance. This is *particularly* useful when the value types are primitives like ints, where you can use SparseIntArray and avoid auto-boxing the values from int to Integer. If you need to construct a HashMap because you need to call an API outside of your control which requires a Map, you can suppress this warning using for example the @SuppressLint annotation.
25.使用静态工厂方法而不是new.
Use Integer.valueOf(temp & 0xff) instead Issue: Looks for usages of "new" for wrapper classes which should use "valueOf" instead Id: UseValueOf You should not call the constructor for wrapper classes directly, such as"new Integer(42)". Instead, call the "valueOf" factory method, such as Integer.valueOf(42). This will typically use less memory because common integers such as 0 and 1 will share a single instance.
24.用一基类的Activity的子类:
The <activity> cn.ditouch.client.activity.BaseFragmentActivity is not registered in the manifest Issue: Ensures that Activities, Services and Content Providers are registered in the manifest Id: Registered Activities, services and content providers should be registered in the AndroidManifext.xml file using <activity>, <service> and <provider> tags. If your activity is simply a parent class intended to be subclassed by other "real" activities, make it an abstract class. http://developer.android.com/guide/topics/manifest/manifest-intro.html
23.android确定及取消按钮顺序
看下运行android lint之后的一个提示吧.:
Layout uses the wrong button order for API >= 14: Create a layout-v14/connect_server.xml file with opposite order: OK button should be on the right (was "OK | Cancel", should be "Cancel | OK")
最后更新 :2012-04-28
22.在android中使用声音效果
Thanks to:http://stackoverflow.com/questions/5236709/sound-effects-on-button-click
最佳答案:
You can use a SoundPool, look here: http://developer.android.com/reference/android/media/SoundPool.html Load the sounds you need into your SoundPool and then use the play() method.
http://www.droidnova.com/creating-sound-effects-in-android-part-2,695.html
写得比较详细.比较好请参考 .
2012-04-22
21.取得当前系统的配置信息,及应用使用了
Configuration cfg = getApplication().getResources().getConfiguration(); int sz = cfg.screenLayout&cfg.SCREENLAYOUT_SIZE_MASK; System.out.println("size: "+sz);
See:http://stackoverflow.com/questions/9271437/why-layout-large-v11-resource-does-not-apply-on-andoid-4-0-wvga800-phone
20,用于ipv4的正则表达式:
^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[09][0-9]|[1-9][0-9]|[0-9])$
Thanks to:http://demon.tw/programming/regex-ipv4.html
19.在ListView项中添加的Button等控件之后要注意的地方:
(1)控件的onClickListener()必要在getView()方法中注册.
(2)要想 ListView中的item还可以使用onItemClickListener()和onItemLongClickListner()的话,需要将
listView中的item布局中的Button等控件设置为focusable="false"
Thanks to: (1)http://www.cnblogs.com/allin/archive/2010/05/11/1732200.html
(2) http://txlong-onz.iteye.com/blog/907186
18. 如何检索android设置的唯一ID
Thanks to:http://articles.csdn.net/badasanxingzhuanqu/jishuwenzhang_Android/2011/0919/304625.html
对于2.2及以后的版本,使用下面的方法简单直接:
ANDROID_ID
说明
更具体地说,Settings.Secure.ANDROID_ID 是一串64位的编码(十六进制的字符串),是随机生成的设备的第一个引导,其记录着一个固定值,通过它可以知道设备的寿命(在设备恢复出厂设置后,该值可能会改变)。ANDROID_ID也可视为作为唯一设备标识号的一个好选择。如要检索用于设备ID 的ANDROID_ID,请参阅下面的示例代码
String androidId = Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID);
缺点
• 对于Android 2.2(“Froyo”)之前的设备不是100%的可靠
• 此外,在主流制造商的畅销手机中至少存在一个众所周知的错误,每一个实例都具有相同的ANDROID_ID。
17.高效的适配器 Efficient Adapter
Thanks to :android docs:docs/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html
使用ViewHolder 模式
具体使用参见上面参考文档.
16.接管BACK按钮事件
Thanks to :http://stackoverflow.com/questions/2000102/android-override-back-button-to-act-like-home-button
@Override public void onBackPressed(){ // do something check // you can also do what onBackPressed do just call super.onBackPressed(); }
15. 在View中携带数据的方式:
使用 View.setTag(Object)
14.检测网络连接状态.
(1 ) 首先确保配置了相应权限.使用如下权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />(2)检测的网络连接状态的示例代码
private boolean checkNetwork() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo == null || !networkInfo.isAvailable()) { // showDialog return false; } else if (networkInfo.getType() != ConnectivityManager.TYPE_WIFI) { Toast.makeText(this, "当前网络连接使用手机流量!,建议使用Wifi!", Toast.LENGTH_LONG); } return true; }
13.设置对话框风格的Acitivity.
只要在acititty属性设置中设置使用对话框主题就可以了.如下:
android:theme="@android:style/Theme.Dialog"
12. 使用include,你可以在书上或者其它地方看到使用include的一个好处就是便于重用.
但是我发现了一个问题,就是当你的界面布局很复杂的时候,布局xml都在一个文件里,使用eclipse的图形布局来预览的时候,根本看来出效果来.得真机才行.但是当布局简单的时候,就可以了.
有一次我是把一个布局的部分copy出来,调试好了之后再放进去,但是你知道吗?这个也很麻烦的.copy来copy去.
解决办法 就是include了.然后就不用copy来copy去了.
我的复杂布局就是因为使用了SlidingDrawer哈哈,下面是引用 handler
<include layout="@layout/order_list_drawer_handler"/>
11. 与TextView有关的布局的优化
在我使用一个布局的时候,eclipse提示了一个警告,我看到如下说明:
This tag and its children can be replaced by one <TextView/> and a compound drawable
然后我搜索了这句话:
在stackoverflow中也有人提到了这个问题:上面说明的很清楚了:
http://stackoverflow.com/questions/3214424/android-layoutopt-this-tag-and-its-children-can-be-replaced-by-one-textview
因为TextView可以设置类似android:drawableLeft,android:drawableRight等等属性.
(我晕一下,我的eclipse居然没有提示上面的这些属性.)
其实,主要一点就是,不要小看了TextView.
从代码行解释这个问题可以参见:
TextView碉堡了!android源代码的一些统计信息!
10.设置自定义的标题栏,
使用如下代码:
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);R.layout.titlebar如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:background="@drawable/title_bar_bg"> <TextView android:id="@+id/title_bar" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="26sp" android:gravity="center" /> </LinearLayout>有一个问题,我无法使用TextView titleBar = (TextView)findViewById(R.id.titlebar)来获得这个titleBar
但是我使用setTitle还是会生效的.(如果我这个layout里面没有TextView会报错吗?)
9.关于布局与焦点:
我发现android处理Layout中的View树的焦点是按照他在Layout中布局顺序来处理的.
例如,在一个相对布局的中我的一个SlidingDrawer想放在最上面使用alignParentTop,下面是一个GridView.
在运行的结果中,GridView会首先得到焦点.而且看起来就会将SlidingDrawer覆盖掉.这个SlidingDrawer也就无法下拉.
但是如下设置GridView在SlidingDrawer的下面的话,那么GridView将显示不出来.暂时不清楚问题本质原因.
哈哈,刚开始我是在GridView上面设置一个比较大的marginTop但是这个还不能很好的解决问题,
为此我花了N多的时间来组合不同的布局,想到过用FrameLayout,FrameLayout确实可以使用.
但是,后来尝试到使用Relative也是可以的.但是我将SlidingDrawer放到GridView的下面.于是SlidingDrawer将覆盖
在GridView的顶部,但是这个没有关系.哈哈.
8. 一个androidView类未公开的可以用于调试View的API。可以打印出View类比较详细有针对性的消息。
/** * Prints information about this view in the log output, with the tag * {@link #VIEW_LOG_TAG}. * * @hide */ public void debug() { debug(0); }号外,我发现android2.3.2中View类的代码为9800多行。而在android4.0.3中代码有15000行。
这个真的伤不起啊。
事实上经过统计排名前十的类文件如下:
banxi1988@banxi:~/android/tmp/android_api_15/android$ find . -type f -name '*.class' -exec du -h {} \;|sort -nr|head 56K ./android/view/View.class 48K ./android/R$attr.class 44K ./android/content/Intent.class 36K ./android/widget/TextView.class 36K ./android/R$style.class 32K ./android/app/Activity.class 28K ./android/widget/AbsListView.class 28K ./android/webkit/WebView.class 28K ./android/view/ViewGroup.class 28K ./android/view/KeyEvent.class
1.让界面默认使用横屏(配置android:screenOrientaion),并且不随自动改变(指定哪些配置变化程序自己处理android:configChanges),如下:
<activity android:name=".OrderClientActivity" android:screenOrientation="landscape" android:configChanges="keyboardHidden|orientation" />2.ViewFlipper显示指定的View(使用setDisplayedChild())
mFlipper.setDisplayedChild(position);3.配置某一个Activity窗口特性如无标题栏,全屏:
参考来自:http://daixu-yang.iteye.com/blog/1096803
(1)可以通过设置活动的主题android:theme为android内部的某些具有无标题栏的特性的主题:如下:
android:theme="@android:style/Theme.Light.NoTitleBar"关键是有NoTitleBar这个的就可以了。
其它的属性如全屏也是这样设置。
(2)通过代码:
如设置无标题栏,要在setConentView()之前调用:
requestWindowFeature(Window.FEATURE_NO_TITLE);设置全屏:
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
4. 啊手贱,我人R文件不见了:
事出起因:是因为我觉得原来项目的包名起得不对于是修改了,没有报错,但是运行的时候报错了,提示找不到类啊。
然后我就仔细看了下,发现他找的还是原来包名的类,于是我仔细看了下,R类文件 所在包的名字就是还是原来的包名。
于是修改之,但是还是不能运行。然后悲剧发生了我发现R类不见了。然后我见Manfifest文件中就是有定义包名,于是 手动改之,然后R文件真的不见了,悲剧啊,于是我不断的clear,重启。最后。
我还是将清单文件中的package改回原来的名字,哈哈,这个出来了,于是我将项目类文件一个一个引用 错误。
(因为不知道怎么的,类中R引用 变成了android.R了。)
然后在项目中使用right click->android tool-> Rename Application Package.
哈哈,这样就可以修改包了。应该要这样 做啊。
结果 手贱啊。改了之后 。
5. 获得LayoutInflater和两种方式:
(1)LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
(2) LayoutInflater mInflater = mInflater = LayoutInflater.from(context);
7. 在我前面的文章:
http://my.oschina.net/banxi/blog/49210
中写到了在查看源代码的时候发现了android有使用@hide的规则。
于是我grep了下源代码看下有还有哪些没有公开的可以公用的API。
banxi1988@banxi:~/android/android-sdk-linux_x86/sources/android-15/android$ grep -l -r @hide . > hide_api.txt这样我就可以看到有多少没有公开的API了。显然我上面是grep了android-15的源代码。