Skip to content
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

Feature/ex 3 #3

Open
wants to merge 23 commits into
base: develop
Choose a base branch
from
Open

Feature/ex 3 #3

wants to merge 23 commits into from

Conversation

nikiJava
Copy link
Owner

View Exercise 3.

Copy link

@colriot colriot left a 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'])
Copy link

Choose a reason for hiding this comment

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

Зачем папку опять добавил? Нужны какие-то внешние джарники?

Copy link
Owner Author

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"
Copy link

Choose a reason for hiding this comment

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

Саппортные либы должны быть одной версии, для чего имеет вынести её в переменную: для cardview и recyclerview

Copy link
Owner Author

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));
Copy link

Choose a reason for hiding this comment

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

Лучше сделать проверку на null, т.к UI может измениться, а об отсутствии тулбара узнаешь уже по крэшу

Copy link
Owner Author

Choose a reason for hiding this comment

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

Специально не проверял на null, поскольку таким образом можно замаскировать собственную или чужую ошибку (кто-то случайно поменял id у тулбара, или вовсе убрал без предупреждения), а так, по крэшу при тестировании я сразу ошибку увижу, что тулбар почему-то не найден на макете, увижу строчку, в которой ошибка.

Copy link

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();
Copy link

Choose a reason for hiding this comment

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

Даже static можно

Copy link
Owner Author

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) {
Copy link

Choose a reason for hiding this comment

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

Вообще похоже на то, что тебе не нужен инстанс. Это просто статический метод, самый обычный.

Copy link
Owner Author

Choose a reason for hiding this comment

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

Если делать метод как static, то в таком случае и вызывать его нужно будет не через инстанс, а через класс. И как явную зависимость этот класс уже не объявишь потом - как такового смысла в этом не будет. Или такие классы с небольшой и просто логикой не стоит всегда указывать, как явную зависимость? Или суть в том, что у этого класса нет состояния и, следовательно, создавать инстанс смысла нет?

Copy link

Choose a reason for hiding this comment

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

Нет состояния, и он больше как Utils-класс. Если бы у тебя была возможность разные конфигурации сделать, подменять реализацию, то да - инстанс

Copy link
Owner Author

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"
Copy link

Choose a reason for hiding this comment

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

Базовые димены хорошо бы вынести в dimens.xml

Copy link
Owner Author

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"
Copy link

Choose a reason for hiding this comment

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

Сделал, чтобы оно растягивалось при ресайзе? Но я не вижу констрейнта на левый край вьюшки. Тогда почему так?

Copy link
Owner Author

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" соответственно).
image

Copy link

Choose a reason for hiding this comment

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

Упустил то, что ширина вью фиксированная. Всё норм с точки зрения реализации, а с точки зрения UX - спорно - картинка будет вертикальная. Размер шрифта может менять, т.е и высотка текста, и высота картинки тоже, а ширина фикси. И ещё: когда будут короткие тексты, у тебя будет помногу пустого места внизу - возможно не есть гут, и данамическая высота была бы лучше.

Copy link
Owner Author

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"
Copy link

Choose a reason for hiding this comment

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

Никогда не хардкодь цвета

Copy link
Owner Author

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"
Copy link

Choose a reason for hiding this comment

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

Размеры то из констант, то хардкод

Copy link
Owner Author

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<>();
Copy link

Choose a reason for hiding this comment

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

Лучше юзать ArrayMap, для более эффективной работы по памяти. Т.к тебе не надо постоянно изменять мапу, а только несколько раз добавить в неё, а потом лишь читать.

Copy link
Owner Author

Choose a reason for hiding this comment

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

Заменил на ArrayMap.

@@ -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>
Copy link

Choose a reason for hiding this comment

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

Если ты прям акцент хочет на цвете сделать (и много где его юзать), то ок.
А вот если тут акцент скорее на назначении, типа "цвет фона карточки", то может лучше именно так его и назвать. Т.к он может поменяться, но не надо будет ещё и название менять (если он станет, например, синим). Но это не обязательно к исправлению, просто имей в виду.

Copy link
Owner Author

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) {
Copy link

Choose a reason for hiding this comment

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

Нет состояния, и он больше как Utils-класс. Если бы у тебя была возможность разные конфигурации сделать, подменять реализацию, то да - инстанс

Copy link

@colriot colriot left a 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"
Copy link

Choose a reason for hiding this comment

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

Упустил то, что ширина вью фиксированная. Всё норм с точки зрения реализации, а с точки зрения UX - спорно - картинка будет вертикальная. Размер шрифта может менять, т.е и высотка текста, и высота картинки тоже, а ширина фикси. И ещё: когда будут короткие тексты, у тебя будет помногу пустого места внизу - возможно не есть гут, и данамическая высота была бы лучше.

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