AndroidStudio常用快捷键

作为一个Android开发者,最常使用的就是Android Studio了,我在这里声明Android Studio比Eclipse好用100倍,不服来辩。本文用于纪录Android Studio中相见恨晚的操作,阅读本文大概需要不确定时间。(你难道就不边读边试试?)我会用尽量简单明了的语言介绍。PS:多图,流量用户慎入。

更新日期 更新内容 备注
2016/9/22 更新Android Studio 2.2 查询示例程序的操作,具体见内容 5
2016/9/17 更新 提取 和 内联 的快捷操作,具体看内容 1.3.2 和 1.3.3 感谢MAIMIHO读者的提供。参考链接:12
2016/7/30 更新更简单的非空输入方法对象.nn
更新Windows版查看类的继承关系快捷键Ctrl+H 感谢3f76b4e62a13的补充
更新活动模版查看和自定义入口Preference->Editor->Live Templates 感谢Sacowiw的提供
2016/7/25 更新大纲 Windows版快捷键Ctrl+F12 感谢Alex_Cin,bryanno1的提供和验证

1 编写

1.1 活动模版

1.1.1 for循环原来可以这样

遍历集合的时候,对象.for就可以生成迭代循环遍历:

.fori可以这样:

.forr可以反向:

数字.for也可以:

1.1.2 判空可以这样

在写代码的时候,判空是不可避免的。判空可以这样,对象.null

非空可以这样,对象.notnull

非空还有更简单的方法,对象.nn

1.1.3 别再写if()了

if可是我们最常用的了,但是我劝你再也不要写if()了,试试任何可以判断的语句后面加上.if:

1.1.4 instance也可以很炫酷

1.1.5 活动模版自定义和查看入口

Preference->Editor->Live Templates,这个窗口下小伙伴们可以看到所有的活动模版,还可以自定义自己的活动模版。例如我就定义了一个tc,作为android:textColor=""的活动模版。

1.2 多行编辑

喜欢用sublime等编辑器的小伙伴对这个应该在熟悉不过了。

1.2.1 多行编辑

例如我们有四个Button要定义,可以先这样,按住alt键+鼠标左键一直向下拉,就可以选中多行,然后编辑就可以同时对多行进行编辑,编辑完相同部分再分别输入不同部分就ok了:

1.2.2 块编辑

比如我们要把上边定义的四个Button 改为TextView类型:

操作也是按住alt不放,拉对角线,拉出一块,就可以对选中的块,进行块编辑了。

1.3 快捷键

1.3.1 Alt+Enter

这个是Android Studio神快捷键。如果你还认为Alt+Enter键是导入包,那就大错特错了。以后有事没事就按下吧。它会根据不同的情况给出操作建议,大大提高工作效率。

eg.

我要获取布局文件中的RecyclerView,findViewById写好了,这个时候需要强制类型转化,在红线上按使用该快捷键,给出了提示Cast to …(此处省略好几个字),再回车,代码生成好了。

接下来是要给RecyclerView设置一个Adapter,那么我先写了没有的PersonAdapter类,那么这个类是没有的,提示红色,我们在该类上使用该快捷键,给出了提示:Create class …,回车,这个类便创建好了。

但是我们要实现RecyclerView.Adapter中的方法,我们在红线部分使用快捷键,看到给出提示implement method,回车,方法实现了。

Alt+Enter快捷键是Android Studio中的神键,它的功能远不止这些,没事就按一按吧。按按更健康。

1.3.2 提取 方法,style,layout等

我在写代码的时候都是先写可用的代码,把功能都实现之后,立即重构,在这个时候我经常用到 提取方法 的这个快捷键:alt+command+M

提取sytle,layout等并没有默认的快捷键。如果你的有,可能我们用的不是同一套,不过无论怎样,你都可以去偏好设置里去自定义快捷键。那么打开keymap。找到Extract,可以看到,包括之前的提取方法操作也在这里,下面的style和Layout就是提取样式和和布局了。你也可以看到还有很多。你可以根据自己的喜好了来自定义快捷键。

演示:

提取布局

提取样式

1.3.3 内联

对于上面我们提取出的方法,样式或者布局,这些都可以使用内联把他们加回使用的地方。这个我并不是很常用。不过还是介绍一下吧。这个默认快捷键是:alt+command+N,在keymap表中的Inline

将布局内联到当前布局

2 搜索

在写代码的过程中,代码检索永远都少不了。如果你是眼睛去找,那效率真的不知道要差到哪里去了。

2.1 搜索基本操作

这些搜索操作我叫做基本操作

操作 Mac Windows
搜索类 Command+O Ctrl+N
文件中搜索 Command+F Ctrl+F
搜索文件 Command+shift+O Ctrl+shift+N
全局查找 Command+shift+F Ctrl+shift+F

要是懒的话,这四个基本可以解决查找问题。

2.2 大纲

大纲快捷键 Mac:Command+F12 Windows:我不知道。。。(我自己用的Mac有些Windows的我也不知道。欢迎补充,PS:我的Mac开启了将Fx键用作标准功能键,如果没有开启的小伙伴,你的快捷键就是Command+Fn+F12),大纲出来了,就可以查看该类中的成员变量和成员方法,直接输入名称就可以筛选查询。

2.3 Search Everywhere

这个功能的强大就如它的名字一样,它的快捷键是双击shift,输入关键字就可以。就连窗口都可以搜索奥。

3 窗口

3.1 分屏

分屏可以上下,可以左右,我更喜欢左右分屏,有的时候很方便。

你可以直接使用Search Everywhere功能,然后输入split会有vertically和Horizontally两种,选择你要的就可以。或者在编辑窗口上的标签,右击,选择split vertically或者split Horizontally。我比较喜欢使用Search Everywhere,键盘总比鼠标快。

3.2 Hierarchy窗口

Hierarchy窗口可以让我们看清楚层级关系,还记得之前非常火的一个段子讲,是好朋友不会让你学Java的,然后附了一张Java继承关系的图,在继承关系层级很深,很复杂的时候,这个窗口简直不能太好。

这个是类的继承关系:

打开这个窗口,可以使用Search Everywhere功能,输入Hierarchy就可以,Mac也可以使用快捷键ctrl+H,Windows快捷键也是ctrl+H。

还有一个Call Hierarchy,可以显示出方法的调用层级关系:

这个的快捷键是ctrl+alt+H。

4 调试

调试过程在开发中也是少不了的。

4.1 快照

有关UI的编程,这个功能知道会省很多事。

在运行过程中,可以给手机截图,并保存。再也不用手机截图然后再传电脑了。

4.2 录屏

在做有关动画的功能的时候,录屏功能可以让你更好的检查动画是否正确。

4.3 断点

断点的使用,断点的用法不止是让程序停下来。试一试在停下来之后使用快捷键Alt+F8,调出Evaluate Expression界面,在该界面你可以输入你想查看的值,就可以显示出来。

除此之外在断点处右击,会出现如下的界面,你可以在图中光标处输入断点停下的条件,当你需要在一个循环中打断点的时候,这简直就是神技:

在上图中Suspend前的勾取消会看到这样的界面:

这个界面上内容更多,比如你选中了Log evaluated expression,然后在下面的输入框中输入你想要输出的log,那么这个断点就不会在这里停下来,而是在控制台输出一条日志。

5 查询示例程序

这个功能让我感觉越来越像代码的搬运工了! 使用该内容需要,Android Studio2.2以及在SDK Manager中下载Samples for SDK,然后重启AS,再然后尽人事听天命,昨天搞了半天就是出不来,不知道今天怎么好了……究竟是AS的灵异事件还是我的努力感动了上天,反正我成功了。

在一个不会用的类上右键,选择Find Sample Code,或者使用你看到的快捷键alt+F8,Windows版的快捷键自己查询。之后就可以方便的查看示例代码。例如我们查看ColorMatrix的示例代码:

查询结果会在下方出现,不过有的时候要等很久,有的还找不到:

不过已经非常不错了。首先有Android官方网站的官方文档。下面会有几个包涵ColorMatrix的栗子。单击可以在右边直接查看其内容。如果硬是出不了的话,又实在想看,那么就去github上去查看吧,有一个组织叫GoogleSample,去搜就行了。

结束语

这篇文章没有结束,正在看的你如果对Android Studio还有其他的相见恨晚的操作,欢迎留言补充。希望这篇文章对大家有帮助。

Android Studio中Make Project,Clean Project,Rebuild Project区别

其实好几个版本的这几个选项都不一样,里面的机理也不同,这里以Android Studio2.1.1为例,亲自验证过,见下图:

屏幕快照 2016-05-24 下午1.44.58         屏幕快照 2016-05-24 下午2.11.13

  1. Make Project:编译Project下所有Module,一般是自上次编译后Project下有更新的文件,不生成apk。
  2. Make Selected Modules:编译指定的Module,一般是自上次编译后Module下有更新的文件,不生成apk。
  3. Clean Project:删除之前编译后的编译文件,并重新编译整个Project,比较花费时间,不生成apk。
  4. Rebuild Project:先执行Clean操作,删除之前编译的编译文件和可执行文件,然后重新编译新的编译文件,不生成apk,这里效果其实跟Clean Project是一致的,这个不知道Google搞什么鬼~~
  5. Build APK:前面4个选项都是编译,没有生成apk文件,如果想生成apk,需要点击Build APK。
  6. Generate Signed APK:生成有签名的apk。

注意:

  1. 对于Clean和Rebuild看到最后的效果是一样的。
  2. 平时小的改动直接用Make Project就可以,可以看到只有它有快捷方式,表明这个功能要经常用。对于一些大的改动比如更新lib,大功能修改等,用Clean或Rebuild,毕竟这两个编译起来要费时间。
  3. 如果有的时候死活编译不过,多试试Clean吧,会有意想不到的效果!

Android Project Structure — alternative way

We all know how android project structure looks like — place all images inside this folder and all layouts inside that folder. But… during project development the number of files grow up rapidly and it becomes hard to navigate and search needed file.

Typical android project structure

Resource folder — per screen

In case if your screens consist of big amount of layouts, drawables, dimensions — it make sense to create separate resource folder for every screen.

Resource folder — per screen android project structure

As you can see on image above we have two root folders inside main folder:

  • res-main contain all common resources which are used on more than one screen.
  • res-screen contain resource folders for every screen e.g. about, chat,event details, event list, home, login

Let’s take a look what we have inside chat screen resource folder.

Resource folder

Chat itself consist of several xml layouts files so we created chat layoutfolder and moved all those files here. It also has a lot of .png images which are used only on chat screen, so we moved all those images files to chat drawable-hdpi, drawable-xhdpi, drawable-xxhdpi and drawable-xxxhdpifolders.

When times come to implement landscape layout or tablet version of chatwe will make layout-land and layout-sw720dp folders inside chat screen resource folder.

How declare screen resource folder?

Open app.gradle file and declare sourceSets inside android section. More about resource merging here.

sourceSets {
    main {
        res.srcDirs = [
                'src/main/res-main',
                'src/main/res-screen/about',
                'src/main/res-screen/chat',
                'src/main/res-screen/event-detail',
                'src/main/res-screen/event-list',
                'src/main/res-screen/home',
                'src/main/res-screen/login',
        ]
    }
}

Instead of declaring all resource files explicitly you can write simple script which will add all sub folders of given folder to srcDirs.

sourceSets {
    main {
        file('src/main/res-screen')
                .listFiles()
                .each { res.srcDirs += it.path }
    }
}

Note: above works only if you are in Project view

Conclusion

If you have a big project and want to arrange your folders, quickly see which layout, drawables, values, etc. belongs to which screen try to use resource folder — per screen android project structure.

Instant Run工作原理

英文链接:https://medium.com/google-developers/instant-run-how-does-it-work-294a1633367f#.xec6ech7y

后面有时间翻译下。

Take Instant Run. It’s a feature in Android Studio that uses ✨magic✨ to significantly reduce the build and deploy times for incremental code changes during your coding / testing / debugging lifecycle.

I say magic, because for the most part that’s how it looks. The first time you hit run or debug, it works like you’d expect — then each time you make a change and hit run or debug again (this time with a ⚡ on the icon), the changes are applied before I’ve had a chance to shift my attention to my phone.

Let’s save the magic for Sunday nights

I prefer my magic to come with a side-helping of dragons, political intrigue, and unexpected beheadings, so I got together with the Android Studio engineering team to get a peek behind the curtain, and learn how Instant Run actually works.

Start with this simple flow chart of a typical build cycle

Build, deploy / install, app launch, Activity started

The goals of Instant Run are really simple:

Remove as many of these steps as possible, and make whatever remains as fast as possible.

In practice that means:

  • Build and deploy only the incremental changes.
  • Don’t reinstall the app.
  • Don’t restart the app.
  • Don’t even restart the Activity.

Hot, Warm, and Cold Swaps aren’t references to games played during 70’s parties. As far as I know.

Instant Run = Incremental build + Hot, Warm, or Cold swap

Hot Swap: Incremental code changes are applied and reflected in the app without needing to relaunch the app or even restart the current Activity. Can be used for most simple changes within method implementations.

Warm Swap: The Activity needs to be restarted before changes can be seen and used. Typically required for changes to resources.

Cold Swap: The app is restarted (but still not reinstalled). Required for any structural changes such as to inheritance or method signatures.

When you hit run or debug, something like this happens

Manifests are merged and combined with resources and .dex files into your APK

Your manifest files are merged and packaged, along with your app’s resources, into an APK. Similarly, your source code .java files are compiled into bytecode, converted to .dex files, and they’re also included within your APK.

The first time you hit Run or Debug with Instant Run enabled, Gradle performs some additional tasks

Instrumentation and an App Server are injected into your debug APK

Bytecode instrumentation is added to your .class files, and a new App Server class is injected into your app.

A new Application class definition is also added, which injects custom class loaders and will start the App Server. Accordingly, your manifest is modified to ensure your app uses it (if you’ve created your own Application class, the Instant Run version will proxy yours.)

Instant Run is now… running, so if your make code changes and hit run or debug again, Instant Run will try to shortcut as much of the full build process as possible using a Hot, Warm, or Cold swap.

Before applying Instant Run changes, Android Studio checks that there’s an open socket to an App Server running within an Instant Run enabled version of your app. It confirms the app is running in the foreground, and that its build ID is the version Android Studio expects.

Hot Swapping

Android Studio monitors which files are changed during development, and runs a custom Gradle task to generate .dex files for only the modified classes.

Those new .dex files are picked up by Android Studio, which deploys it to the App Server running within our app.

Because the original versions of our classes already exist in the running app instance — Gradle has transformed the “updated” versions such that they effectively override those pre-existing classes. Those transformed, updated classes are then loaded by the App Server using the custom class loaders.

From now on, each time a method gets called — anywhere within our app — the instrumentation injected into our original class files communicates with the App Server to see if they’ve been updated.

If so, execution is delegated to the new “override” classes and the new, modified, version of the method will execute instead.

If you set breakpoints you’ll see the “override”-named classes’ method calls in your stack trace.

Redirecting methods works well for changes to method implementations, but what about things that are loaded when the Activity starts?

Warm Swapping

A warm swap restarts the Activity. Resources are loaded when Activities are started, so modifying them requires an Activity restart to force a resource reload.

Currently, changes to any resource results in all of them being re-packaged and transmitted to your app — but we’re working on an incremental packager that will only package and deploy new or modified resources.

Note that a warm swap won’t work for changes to resources referenced within the Manifest — or changes to the manifest itself — because Manifest values are read when the APK is installed. Changes to the Manifest (or manifest-referenced resources) will trigger a full build and deploy.

Unfortunately, restarting the Activity won’t magically apply structural changes. Adding, removing, or changing annotations, fields, static or instance method signatures, or changing parent classes or static initializers will require a Cold Swap.

Cold Swaps

When deployed, your app and it’s sub-projects are divided into up to 10 slices, each its own dex file; classes are allocated to slices based on their package names. When applying a cold swap, a modified class will require all the other classes within the same slice to also be redexed before that slice is deployed to the target device.

This approach depends on the Android Runtime being capable of loading multiple .dex files, a feature introduced with ART, which is only guaranteed on Android 5.0 (API level 21) devices and higher.

For target devices running API level 20 or lower — and therefore possibly using the DALVIK runtime, Android Studio deploys a full APK.

Instant Run is clever, but it can’t turn back time

Code changes that might otherwise be applied through a Hot Swap, but which affect initializers that were run when the application was first run, you’ll need to restart your app for the changes to take effect.

To perform an incremental build and restart the app, click Rerun (CTRL-CMD-r) from the toolbar.

Instant Run Tips and Tricks

Instant Run is controlled by Android Studio, so only start / restart your debug instance from the IDE — don’t start / restart your app from the device or things will get out of whack quickly.

A more detailed list of tips and tricks is available from the Android Documentation, but here’s a few bullet points to keep in mind.

  • Tweak the resources you’re allocating to the Gradle process. If you have at least 2 gig assigned to the Gradle Daemon JVM via the jvmargs setting in the gradle.properties file, dex-in-process will be enabled, and will dramatically improve the speed of all builds — Instant Run and full / clean builds. You’ll want to experiment and observe the effect on your build times to find the value for you.
  • The availability of ART in Android 21 means you’ll get the most out of Instant Run by setting your minSdkVersion to 21 or higher. You can create a new product flavor specifically for debugging that sets your minSDK to 21.
  • Remember that changes to the manifest will trigger a full build and deploy cycle — so, if your build process automatically updates any part of the app manifest (for example automatically iterating versionCode or versionName) — you’ll want to disable that behavior in your debug build variants.
  • Instant Run currently only instruments the main process, so if your app uses multiple processes, Hot and Warm swaps on the other processes will degrade to cold swaps — or full builds if you’re targeting an API Level less than 21.
  • If you’re on Windows, Windows Defender Real-Time Protection might be causing Instant Run slowdowns. You can get around that by adding your project folder to the list of Windows Defender exclusions.
  • As of this recording, Instant Run didn’t support the Jack compiler, Instrumentation Tests, or deploying to multiple devices simultaneously.

Instant Run is constantly evolving, with the team exploring new techniques to maximize the number of cases that allow for a hot swap, and minimizing the need for cold swaps or full builds.

Android Studio 2.1新特性: 使用Dex In Process加快编译速度

整理自:https://medium.com/google-developers/faster-android-studio-builds-with-dex-in-process-5988ed8aa37e#.52h9ypmgz

  1. 新发布的Android Studio 2.1增加了一个新的特性:Dex In Process,可以极大的加快重新编译的速度,同样也能提高Instant Run的性能。

2. 要开启该功能,需要修改本地工程下的gradle.properties文件,将Gradle Daemon VM的内存增加1G,最少值为2G。即增加如下字段:

org.gradle.jvmargs=-Xmx2048m

增加Gradle Daemon JVM 内存到至少 2G

Gradle Daemon VM 默认分配的内存是1G,  这对dexInProcess来说是不够的, 至少要分配2 G.

3. Dex in process 允许多个 DEX processes 运行在一个单独的 VM,该VM 与Gradle也共享内存, 这也是为什么要为DexInProcess分配额外内存的原因,该内存在Gradle与多个DEX processes共享.

4. 注意的是,如果之前有在项目的build.gradle文件中修改 javaMaxHeapSize大小,超过默认的1G, 你必须相应的增加分配给 Gradle Daemon的内存。

5. 如果可以被分配到足够的内存,Dex in Process默认下被开启, 这会提高整个app的编译效率,减少经常性的启动多个并行VM实例。结果显示这显著改进了编译时间,包括Instant Run,增量编译,全部编译等。