Skip to content

Conversation

iButrimov
Copy link

Исправленный перевод на kotlin

Comment on lines +21 to 24
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а зачем тебе второй интент фильтр LAUNCHER?) У нас только одна стартовая активити - это MainActivity

Comment on lines +11 to +13
private var greetings: String? = null
private var name: String? = null
private var textView: TextView? = null

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

если нам известно, что при создании активности эти поля в любом случае будут иметь значение, то можно возпользоваться отложенной инициализацией:
private lateinit var textView: TextView
это позволит нам не указывать начальное значение и обозначать поле non-nullable типом, что в дальнейшем не будет заставлять нас применять !! или ?. для его обработки

} else {
getString(R.string.anon)
}
textView = findViewById(R.id.textViewHello)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если в котлине появляется IF с условием что-то ==/!= null - то скорее всего игнорируется одна из главных фичей котлина)
можно записать это намного лакончинее:
name = savedInstanceState?.getString(NAME_KEY) ?: getString(R.string.anon)

}
textView = findViewById(R.id.textViewHello)

val button: Button = findViewById(R.id.buttonNameYourSelf)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

о findViewById нужно знать, но в следующий раз лучше сразу использовать View Binding, ну или Kotlin Synthetic

Comment on lines +36 to +41
if (requestCode == SecondActivity.GET_NAME_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
val nameFromData: String? = data.getStringExtra(SecondActivity.NAME_KEY)
if (nameFromData != null) {
name = nameFromData
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

опять же, безопасные вызовы позволят нам сделать код лаконичнее и уменьшить обрамляющее условие:
if (requestCode == SecondActivity.GET_NAME_REQUEST_CODE && resultCode == RESULT_OK)
data?.getStringExtra(SecondActivity.NAME_KEY)?.let { name = it }

@SuppressLint("SetTextI18n")
override fun onResume() {
super.onResume()
textView?.text = "$greetings, $name!"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а если бы textView был определён как lateinit, то можно было бы избежать безопасного вызова

}

override fun afterTextChanged(editable: Editable) {
button.isEnabled = !TextUtils.isEmpty(editable)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

у библиотеки kotlin есть удобные extension методы для работы со строками:
button.isEnabled = editable.isNotEmpty()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants