Skip to content
This repository has been archived by the owner on Mar 1, 2021. It is now read-only.

Igor Lopatinskiy #23

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:recyclerview-v7:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
Expand Down
132 changes: 132 additions & 0 deletions app/src/main/java/ru/ok/technopolis/students/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,145 @@

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Toast;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

private StudentAdapter adapter;
private ImageView photo;
private int photoId;
private EditText firstName;
private EditText lastName;
private RadioGroup radioGroup;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

RecyclerView recyclerView = findViewById(R.id.activity_main__list);
adapter = new StudentAdapter(this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);

photo = findViewById(R.id.activity_main__photo);
firstName = findViewById(R.id.activity_main__firstName);
lastName = findViewById(R.id.activity_main__lastName);
radioGroup = findViewById(R.id.activity_main__radio);

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
randomizePhoto();
}
});

Button addButton = findViewById(R.id.activity_main__add);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearFields();
adapter.setActiveStudent(adapter.NO_STUDENT);
Copy link

Choose a reason for hiding this comment

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

NO_STUDENT статичное поле, можно обращаться прямо через класс

Copy link
Author

Choose a reason for hiding this comment

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

Пофиксил

}
});

Button saveButton = findViewById(R.id.activity_main__save);
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveStudent();
}
});

Button deleteButton = findViewById(R.id.activity_main__delete);
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteStudent();
}
});

}

private void deleteStudent() {
adapter.deleteStudent();
}

private void saveStudent() {

Copy link

Choose a reason for hiding this comment

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

Следи за лишними строками

Copy link
Author

Choose a reason for hiding this comment

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

Пофиксил
Казалось, что так более читабельно)

String firstNameStr = firstName.getText().toString();
Copy link

Choose a reason for hiding this comment

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

firstName.getText() может вернуть null

Copy link
Author

Choose a reason for hiding this comment

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

Пофиксил

Copy link

Choose a reason for hiding this comment

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

Нужно ли в названии переменно пояснять что это стринг?

Copy link
Author

@IgorLo IgorLo Apr 11, 2019

Choose a reason for hiding this comment

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

У меня уже есть переменная firstName, в которой хранится само поле ввода
Если не пояснять, что это стринг, то придётся назвать ту переменную firstNameField
В итоге так или иначе нужно пояснять
Не знаю, как лучше сделать)

String lastNameStr = lastName.getText().toString();
Boolean gender = null;
switch (radioGroup.getCheckedRadioButtonId()){
case R.id.activity_main__radio_male:
gender = true;
break;
case R.id.activity_main__radio_woman:
gender = false;
break;
}

if (firstNameStr.isEmpty() || lastNameStr.isEmpty() || gender == null){
Toast.makeText(this, "Заполните все поля", Toast.LENGTH_SHORT).show();
return;
}

Student student = new Student(
firstNameStr,
lastNameStr,
gender,
photoId
);
adapter.saveStudent(student);
}

private void randomizePhoto() {
int[] imgMale = {R.drawable.male_1, R.drawable.male_2, R.drawable.male_3};
int[] imgFemale = {R.drawable.female_1, R.drawable.female_2, R.drawable.female_3};

int i;
switch (radioGroup.getCheckedRadioButtonId()) {
case R.id.activity_main__radio_male:
i = new Random().nextInt(3);
photo.setImageDrawable(getResources().getDrawable(imgMale[i]));
photoId = imgMale[i];
break;
case R.id.activity_main__radio_woman:
i = new Random().nextInt(3);
photo.setImageDrawable(getResources().getDrawable(imgFemale[i]));
photoId = imgFemale[i];
break;
default:
photoId = imgMale[0];
break;
}
}

public void clearFields() {
photo.setImageDrawable(null);
firstName.setText("");
lastName.setText("");
radioGroup.clearCheck();
}

public void setActiveStudent(Student student) {
photo.setImageDrawable(getResources().getDrawable(student.getPhoto()));
firstName.setText(student.getFirstName());
lastName.setText(student.getSecondName());
if (student.isMale()){
radioGroup.check(R.id.activity_main__radio_male);
} else {
radioGroup.check(R.id.activity_main__radio_woman);
}
}

}
19 changes: 13 additions & 6 deletions app/src/main/java/ru/ok/technopolis/students/Student.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ public class Student {

private String firstName;
private String secondName;
private boolean maleGender;
private boolean isMale;
Copy link

Choose a reason for hiding this comment

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

обычно называют переменную male, что бы геттер можно было назвать isMale
С твоим названием, сеттер должен иметь название не setMale а setIsMale

Copy link
Author

Choose a reason for hiding this comment

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

Назвал "male"

private int photo;

public Student(String firstName, String secondName, boolean maleGender, int photo) {
this.firstName = firstName;
this.secondName = secondName;
this.maleGender = maleGender;
this.isMale = maleGender;
this.photo = photo;
}

Expand All @@ -30,12 +30,12 @@ public void setSecondName(String secondName) {
this.secondName = secondName;
}

public boolean isMaleGender() {
return maleGender;
public boolean isMale() {
return isMale;
}

public void setMaleGender(boolean maleGender) {
this.maleGender = maleGender;
public void setMale(boolean male) {
this.isMale = male;
}

public int getPhoto() {
Expand All @@ -45,4 +45,11 @@ public int getPhoto() {
public void setPhoto(int photo) {
this.photo = photo;
}

public void copy(Student student) {
this.firstName = student.firstName;
Copy link

Choose a reason for hiding this comment

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

Не забывай что присваивая значение объекта ты не копируешь его, а лишь устанавливаешь ссылку

Copy link
Author

Choose a reason for hiding this comment

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

Пофиксил, но не уверен что правильно

this.secondName = student.secondName;
this.isMale = student.isMale;
this.photo = student.photo;
}
}
99 changes: 99 additions & 0 deletions app/src/main/java/ru/ok/technopolis/students/StudentAdapter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package ru.ok.technopolis.students;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.StudentViewHolder> {

public static final int NO_STUDENT = -1;
private MainActivity context;
Copy link

Choose a reason for hiding this comment

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

Плохой паттерн передавать активити в адаптер. Для работы с активити у тебя есть лисенеры

private List<Student> students = new LinkedList<>();
Copy link

Choose a reason for hiding this comment

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

Тут нужен именно LinkedList?

Copy link
Author

Choose a reason for hiding this comment

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

Делал LinkedList опираясь на то, что студентов будут часто удалять
Думаю, разумнее будет всё же ArrayList, так как чаще всего элементы достаются из списка, чем удаляются
Переделал

private int activeStudent = NO_STUDENT;

public StudentAdapter(Context context) {
this.context = (MainActivity) context;
}

public void saveStudent(Student student) {
if (activeStudent == NO_STUDENT) {
students.add(student);
activeStudent = students.size() - 1;
notifyItemInserted(activeStudent);
} else {
Student oldStudent = students.get(activeStudent);
oldStudent.copy(student);
notifyItemChanged(activeStudent);
}
}

public void deleteStudent() {
if (activeStudent != NO_STUDENT) {
students.remove(activeStudent);
notifyItemRemoved(activeStudent);
activeStudent = NO_STUDENT;
}
context.clearFields();
}

public void setActiveStudent(int activeStudent) {
this.activeStudent = activeStudent;
}

@NonNull
@Override
public StudentViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater
.from(viewGroup.getContext())
.inflate(R.layout.recycler_item, viewGroup, false);
return new StudentViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull StudentViewHolder studentViewHolder, int i) {
studentViewHolder.bind(students.get(i));
}


@Override
public int getItemCount() {
return students.size();
}

public class StudentViewHolder extends RecyclerView.ViewHolder {

private ImageView face;
private TextView fullName;

public StudentViewHolder(@NonNull View itemView) {
super(itemView);
face = itemView.findViewById(R.id.recycler_item__image);
fullName = itemView.findViewById(R.id.recycler_item__text);

itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
activeStudent = getAdapterPosition();

Student student = students.get(getAdapterPosition());
context.setActiveStudent(student);
}
});
}

private void bind(Student student) {
face.setImageDrawable(context.getResources().getDrawable(student.getPhoto()));
fullName.setText(student.getFirstName() + " " + student.getSecondName());
}
}
}
13 changes: 13 additions & 0 deletions app/src/main/java/ru/ok/technopolis/students/StudentHolder.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package ru.ok.technopolis.students;
Copy link

Choose a reason for hiding this comment

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

Зачем нужен этот класс?

Copy link
Author

Choose a reason for hiding this comment

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

Случайно оставил
Теперь удалил


import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;

public class StudentHolder extends RecyclerView.ViewHolder {

public StudentHolder(@NonNull View itemView) {
super(itemView);
}

}
Loading