-
Notifications
You must be signed in to change notification settings - Fork 0
Feature/ex 3 #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: develop
Are you sure you want to change the base?
Feature/ex 3 #3
Conversation
…different items height.
…esult of branches merging).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Отревьюил
app/build.gradle
Outdated
compileOptions { | ||
sourceCompatibility JavaVersion.VERSION_1_8 | ||
targetCompatibility JavaVersion.VERSION_1_8 | ||
} | ||
} | ||
|
||
dependencies { | ||
implementation fileTree(dir: 'libs', include: ['*.jar']) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Зачем папку опять добавил? Нужны какие-то внешние джарники?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Убрал папку.
app/build.gradle
Outdated
compileOptions { | ||
sourceCompatibility JavaVersion.VERSION_1_8 | ||
targetCompatibility JavaVersion.VERSION_1_8 | ||
} | ||
} | ||
|
||
dependencies { | ||
implementation fileTree(dir: 'libs', include: ['*.jar']) | ||
implementation "androidx.cardview:cardview:1.0.0" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Саппортные либы должны быть одной версии, для чего имеет вынести её в переменную: для cardview и recyclerview
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вынес в отдельную переменную.
super.onCreate(savedInstanceState); | ||
setContentView(R.layout.activity_news_details); | ||
news = (News) getIntent().getSerializableExtra(NEWS_KEY); | ||
setSupportActionBar(findViewById(R.id.toolbar)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Лучше сделать проверку на null
, т.к UI может измениться, а об отсутствии тулбара узнаешь уже по крэшу
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Специально не проверял на null, поскольку таким образом можно замаскировать собственную или чужую ошибку (кто-то случайно поменял id у тулбара, или вовсе убрал без предупреждения), а так, по крэшу при тестировании я сразу ошибку увижу, что тулбар почему-то не найден на макете, увижу строчку, в которой ошибка.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Подход имеет смысл. Зависит от перспективы и приоритетов.
Добро 👍 Классно, что оспариваешь комменты и аргументируешь!
public class NewsDetailsActivity extends AppCompatActivity { | ||
|
||
private static String NEWS_KEY = "news_key"; | ||
private final DateFormatter dateFormatter = new DateFormatter(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Даже static
можно
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Согласен - нет смысла каждый раз создавать новый инстанс объекта при открытии экрана.
|
||
public class DateFormatter { | ||
|
||
public CharSequence formatDateTime(Context context, Date dateTime) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вообще похоже на то, что тебе не нужен инстанс. Это просто статический метод, самый обычный.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Если делать метод как static, то в таком случае и вызывать его нужно будет не через инстанс, а через класс. И как явную зависимость этот класс уже не объявишь потом - как такового смысла в этом не будет. Или такие классы с небольшой и просто логикой не стоит всегда указывать, как явную зависимость? Или суть в том, что у этого класса нет состояния и, следовательно, создавать инстанс смысла нет?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Нет состояния, и он больше как Utils-класс. Если бы у тебя была возможность разные конфигурации сделать, подменять реализацию, то да - инстанс
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Исправил метод на static
android:id="@+id/tvBody" | ||
android:layout_width="0dp" | ||
android:layout_height="wrap_content" | ||
android:layout_marginTop="16dp" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Базовые димены хорошо бы вынести в dimens.xml
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Константы использовал только для паддингов. Для layout_margin константы не использовал, так как все вьюшки внутри ConstraintLayout располагаются.
<ImageView | ||
android:id="@+id/ivImage" | ||
android:layout_width="100dp" | ||
android:layout_height="0dp" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Сделал, чтобы оно растягивалось при ресайзе? Но я не вижу констрейнта на левый край вьюшки. Тогда почему так?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Чтобы высота картинки была всегда одинаковой - top вьюшки всегда был на уровне top'a заголовка (tvTitle), а bottom вьюшки был на уровне bottom'a описания новости (tvBody). Чтобы такое поведение обеспечивалось, для заголовка и описания задал фиксированное количество строк (android:lines="2" и android:lines="3" соответственно).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Упустил то, что ширина вью фиксированная. Всё норм с точки зрения реализации, а с точки зрения UX - спорно - картинка будет вертикальная. Размер шрифта может менять, т.е и высотка текста, и высота картинки тоже, а ширина фикси. И ещё: когда будут короткие тексты, у тебя будет помногу пустого места внизу - возможно не есть гут, и данамическая высота была бы лучше.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Сделал с помощью барьеров для картинки соотношение высоты к ширине как 1:1 - позволило избавиться от жёстко указанной ширины. На мой взгляд - это всё же минус, когда в одном и том же списке у одинаковых айтемов высота картинки будет разной, поскольку будет зависеть от размера заголовка и дескрипшена. Возможно, что это уже субъективной вопрос, но опыт пользования различными новостными приложениями да и просто приложениями, где есть список, подсказывает, что картинка всё должна быть одинаковой на всех айтемах. Да и желательно квадратной (1:1).
android:id="@+id/tvTitle" | ||
android:layout_width="0dp" | ||
android:layout_height="wrap_content" | ||
android:background="#b4c6c5c5" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Никогда не хардкодь цвета
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Убрал цвет константу.
android:layout_width="wrap_content" | ||
android:layout_height="wrap_content" | ||
android:layout_marginStart="16dp" | ||
android:layout_marginTop="8dp" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Размеры то из констант, то хардкод
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Константы использовал только для паддингов. Для layout_margin константы не использовал, так как все вьюшки внутри ConstraintLayout располагаются.
private int count; | ||
|
||
public Builder() { | ||
typeToAdapterMap = new SparseArray<>(); | ||
typeToAdapterMap = new HashMap<>(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Лучше юзать ArrayMap, для более эффективной работы по памяти. Т.к тебе не надо постоянно изменять мапу, а только несколько раз добавить в неё, а потом лишь читать.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Заменил на ArrayMap.
…e new instance of it every time.
…memory efficiency
app/src/main/res/values/colors.xml
Outdated
@@ -4,4 +4,5 @@ | |||
<color name="colorPrimaryDark">#ffd4a515</color> | |||
<color name="colorAccent">#ff962326</color> | |||
<color name="window_background">?android:attr/colorBackground</color> | |||
<color name="background_transparent_grey">#b4c6c5c5</color> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Если ты прям акцент хочет на цвете сделать (и много где его юзать), то ок.
А вот если тут акцент скорее на назначении, типа "цвет фона карточки", то может лучше именно так его и назвать. Т.к он может поменяться, но не надо будет ещё и название менять (если он станет, например, синим). Но это не обязательно к исправлению, просто имей в виду.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Создал отдельную константу для фона заголовка карточки
|
||
public class DateFormatter { | ||
|
||
public CharSequence formatDateTime(Context context, Date dateTime) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Нет состояния, и он больше как Utils-класс. Если бы у тебя была возможность разные конфигурации сделать, подменять реализацию, то да - инстанс
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В целом approve. Есть мелкие замечания в ответах на комменты, то не критичны
<ImageView | ||
android:id="@+id/ivImage" | ||
android:layout_width="100dp" | ||
android:layout_height="0dp" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Упустил то, что ширина вью фиксированная. Всё норм с точки зрения реализации, а с точки зрения UX - спорно - картинка будет вертикальная. Размер шрифта может менять, т.е и высотка текста, и высота картинки тоже, а ширина фикси. И ещё: когда будут короткие тексты, у тебя будет помногу пустого места внизу - возможно не есть гут, и данамическая высота была бы лучше.
DateFormatter has no behaviour and so it is most preferably to not create redundant instances.
it helps to save scroll position in time of orientation changing.
View Exercise 3.