Android代码规范+小技巧

配置篇

  • layout的xml 命名 :以xml类型+”_”开头

    example:activity_Login.xml
    fragment_home.xml
    item_adapter_order.xml

  • 在xml使用xmlns:tools=http://schemas.android.com/tools ,方便调试,开发

    除了text之外,还可以使用visiable等属性

  • xml控件规范
    android:id 明显应该在layout文件中第一行
    android:style 放在最后一行

  • 单位
    文字大小的单位应该统一用sp,其他元素用dp。因为这两个单位是与设备分辨率无关的,能够解决在不同分辨率设备上显示效果不同的问题。

  • 如果设置layout_weight=1 那么你的layout_width或layout_height 就不要设置能“match_parent”,设置成0dp以便在测量时做出更好的优化

  • xml的根目录为时,可以用代替,因为activity的父元素就是FrameLayout。当Inflate以开头的布局文件时,必须指定一个父ViewGroup,并且必须设定attachToRoot为true(参看inflate(int,android.view.ViewGroup, Boolean)方法)

代码篇

  • 不要将Context 变量设置为static

  • 在activity中写内部类,一定要把内部类设置为static

  • 保存sharedPreference时,建议用apply()代替commit()(不考虑线程安全的情况下);另外apply没有返回值,而commit返回boolean表明修改是否提交成功;

  • 遵守字段命名惯例:
    非public的、非static的字段名称以m开头。
    static字段名称以s开头。
    其它字段以小写字母开头。
    public static final字段(常量)全部字母大写并用下划线分隔。

//examplepublic class MyClass {    public static final int SOME_CONSTANT = 42;    public int publicField;    private static MyClass sSingleton;    int mPackagePrivate;    private int mPrivate;    protected int mProtected;}
  • 不要在底层的方法中处理异常,应该向方法的调用者抛出异常。

更多相关文章

  1. JavaWeb + mySQL + Android(安卓)实现Android简单的注册登录
  2. android(3)
  3. Android使用注解避免大量的findViewById()
  4. android sqlite查询数据表的字段与相关属性
  5. android通过自定义toast实现悬浮通知效果的示例代码
  6. android fragment用get/setArguments()传值
  7. Android(安卓)Kotlin入门-属性和字段
  8. Android(安卓)Gson 操作
  9. Android短信操作(通过内容提供者)

随机推荐

  1. android setting 設置<一>
  2. Android产生一个提示框
  3. Android5.0挂载子系统
  4. Phone双模修改涉及文件列表
  5. android百度地图 覆盖物弹出层效果
  6. android的UriMatcher类
  7. Android之Selector、Shape介绍
  8. Android(安卓)P WMS addwindow流程
  9. android中获取网络图片
  10. RadioButton 带下划线切换的案例