Android Studio提交上的自动代码改进

如您所知,在Android Studio中有两种使用git的方法。



第一种经典方法是使用控制台。这种方法的优势首先是可靠性。GUI可能卡住,例如在变基阶段冻结,因此中止/继续/切换到另一个分支将无济于事。控制台命令将为您提供帮助,它们始终无故障。



第二种方法是使用Android Studio提供的GUI。优点是显而易见的-较低的进入门槛,更清楚了该做什么。为了方便使用git,工作室还提供了各种面包。将讨论其中之一。顺便说一句,使用GUI,您也可以不使用鼠标并使用热键



本文中使用的热键



Shift + Shift(双击Shift)-搜索窗口。允许您搜索代码/资源以及各种操作和设置。



Ctrl + Alt + L(⌘+⌥+ L)->代码格式



Shift + Ctrl + Alt + L(⇧+⌘+⌥+ L)→代码格式→带参数的代码格式。



调用此窗口

图片



这是什么一回事,在哪里找到?



不相关的导入,空行,空格而不是制表符-如果这些事情最终出现在用于拉取请求的就绪代码中,则会令人发指。使用热键Ctrl + Alt + L可以很容易地解决此问题,但是我们经常忘记这样做。

Idea / AndroidStudio允许您在提交前的最后一刻自动执行这些操作



通过Android Studio使用提交时,您会看到一个类似以下的窗口:



我们对“提交前”块中文件列表右侧的复选框感兴趣。激活这些助手后,它们将自动应用于每次提交



这些复选标记对我有什么帮助?



✓重新格式化代码



这项改进使代码与您的代码样式相匹配。该操作与启用清除功能的ctrl + shift + alt + L完全相似。



您可以在此处自定义代码样式设置→编辑器→代码样式



Tab and Indents

根据代码样式应用行缩进(有关详细信息,请参见相同名称部分的代码样式)



在示例中,用于形成缩进的空间(用点标记)将被制表符(用箭头标记)代替

提交之前



class CleanTab(context: Context) {

....val date = Date()

....val button = Button(context)
....val textView = TextView(context)
....val ratingBar = RatingBar(context)
....val imageView = ImageView(context)
}


提交后



class CleanTab(context: Context) {

-> val date = Date()

-> val button = Button(context)
-> val textView = TextView(context)
-> val ratingBar = RatingBar(context)
-> val imageView = ImageView(context)
}


Spaces

code-style.



Date, button =, args main {



class CleanSpaces(context:Context) {

    val date = Date( )

    val button= Button(context)

    fun main(arg: Args){

    }
}




class CleanSpaces(context: Context) {

    val date = Date()

    val button = Button(context)

    fun main(arg: Args) {

    }
}


Wrapping and Braces

. , / .



else, catch , ( code style)

manyArguments 80 ( code style),



class CleanWrappingAndBraces {

    fun condition() {
        if (liveData != null) {
            <..>
        }
        else {
            <..>
        }
    }

    fun catching() {
        try {
            <..>
        }
        catch (e: Exception) {
            <..>
        }
    }

    fun manyArguments(userId: Int, issuerCountryId: String, sendingCountryId: String, receivingCountryId: String) {

    }
}




class CleanWrappingAndBraces {

    fun condition() {
        if (liveData != null) {
            <..>
        } else {
            <..>
        }
    }

    fun catching() {
        try {
            <..>
        } catch (e: Exception) {
            <..>
        }
    }

    fun manyArguments(userId: Int, issuerCountryId: String,
                    sendingCountryId: String,
                    receivingCountryId: String) {

}


Blank Lines

. ( Code Style, )



}, 2



class CleanBlank {

    fun foo() {

    }

    fun bar() {

    }

}




class CleanBlank {

    fun foo() {

    }

    fun bar() {

    }

}


Rearrange code



, -. XML HTML . Setting → Editor → CodeStyle → XML/HTML → Arrangement



! . Rearrange , , . : LinearLayout, , Button TextView, . —


xmlns , code-style(xmlns:android , xmlns:<...> .

, xmlns:tools xmlns:app , . , rearrange



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    xmlns:tools="http://schemas.android.com/tools" android:layout_height="match_parent"
    android:orientation="vertical" xmlns:app="http://schemas.android.com/apk/res-auto">

</LinearLayout>




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

</LinearLayout>


android:padding code-style. style android:id



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="8dp"
        android:paddingBottom="8dp"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        tools:srcCompat="@tools:sample/avatars" />

    <TextView
        style="@style/TextAppearance.MaterialComponents.Body1"
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World" />

</LinearLayout>




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="8dp"
        android:paddingTop="8dp"
        android:paddingRight="8dp"
        android:paddingBottom="8dp"
        tools:srcCompat="@tools:sample/avatars" />

    <TextView
        android:id="@+id/title"
        style="@style/TextAppearance.MaterialComponents.Body1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World" />

</LinearLayout>


Optimize import



, code style. ctrl+shift+alt+L optimize import.



optimize imports import java.util.* , ,



import android.content.Context
import android.widget.Button
import java.util.*

class RemoveUnused(context: Context) {

    val button = Button(context)
}




import android.content.Context
import android.widget.Button

class RemoveUnused(context: Context) {

    val button = Button(context)
}


n , .

m enum java static ,



Settings → Editor → Code Style → Kotlin → Imports



android.widget android.widget.*



import android.content.Context
import android.widget.Button
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import android.widget.RatingBar
import java.util.*

class MergeImport(context: Context) {

    <..>
}




import android.content.Context
import android.widget.*
import java.util.*

class MergeImport(context: Context) {

    <..>
}


, (m = 0, n=0), ( ) // .

import android.widget. import java.util.



import android.content.Context
import android.widget.*
import java.util.*

class MergeImport(context: Context) {

    <..>




import android.content.Context
import android.widget.Button
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import android.widget.RatingBar
import java.util.*

class MergeImport(context: Context) {

    <..>
}


, ,



import android.content.Context
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import java.util.*
import android.widget.RatingBar

class SortImport(context: Context) {

    <..>
}




import android.content.Context
import android.widget.Button
import android.widget.ImageView
import android.widget.RatingBar
import android.widget.TextView
import java.util.*

class SortImport(context: Context) {

    <..>
}


Perform code analysis



. . — , , , Deprecated



fun TextView.format(message: String) {
   val htmlText = Html.fromHtml(message)
}


, :



Review :



Check TODO



, TODO, . , //TODO, //FIXME, todo, Setting → Editor → TODO.



todo, .



, todo. review todo



Clean up



. (. ), deprecated . Actions → Code cleanup. , .



:



  • deprecated ( )
  • view


! , !


Redutant code
-, .. non-nullable



data class User(val firstName: String, val secondName: String)

val user = User("", "")

fun getUserFullName(): String {
    val firstName = user?.firstName
    val secondName = user.secondName ?: return firstName

    return "$firstName $secondName"
}




data class User(val firstName: String, val secondName: String)

val user = User("", "")

fun getUserFullName(): String {
    val firstName = user.firstName
    val secondName = user.secondName

    return "$firstName $secondName"
}


public, ..



data class User(val firstName: String, val secondName: String)

val user = User("", "")

public fun getUserFullName(): String {
    val firstName = user.firstName
    val secondName = user.secondName

    return "$firstName $secondName"
}




data class User(val firstName: String, val secondName: String)

val user = User("", "")

fun getUserFullName(): String {
    val firstName = user.firstName
    val secondName = user.secondName

    return "$firstName $secondName"
}




class ExecutionClass(val exec: () -> Unit)

val exec = ExecutionClass() {
    doIt()
}




class ExecutionClass(val exec: () -> Unit)

val exec = ExecutionClass {
    doIt()
}


Deprecated

deprecated ReplaceWith(), cleanup . , — , ReplaceWith(). . / . / , ( ), , , . ,





@Deprecated(" ", ReplaceWith("newMethod()"))
fun oldMethod() = Unit

fun newMethod() = Unit

@Deprecated(" ", ReplaceWith("NewClass"))
class OldClass

class NewClass

class GetDeprecatedCodeUseCase(val clazz: OldClass) {

    init {
        val initData = oldMethod()
    }
}




@Deprecated(" ", ReplaceWith("newMethod()"))
fun oldMethod() = Unit

fun newMethod() = Unit

@Deprecated(" ", ReplaceWith("NewClass"))
class OldClass

class NewClass

class GetDeprecatedCodeUseCase(val clazz: NewClass) {

    init {
        val initData = newMethod()
    }
}




, Android Studio . , , , . , .



:



Optimize import Reformat code . .



Rearrange Clean up . , - , (Rearrange) (Clean up)



Check TODOPerform代码分析也可以毫不费力地使用。它们不会以任何方式影响代码,它们只会给出令人讨厌的提示。是的,如果您项目中的所有内容都完全基于TODO和不推荐使用的代码构建,那么它们将永远没有尽头,而且它们会更令人讨厌。但是,如果您的项目中有相当干净的代码,并且您尝试将此类时间减至最少,那么助手将为您提供一个极好的机会来修改您可能遗漏的代码。




All Articles