Пытаюсь сделать приложение singleActivity(Учусь). Пытаюсь сделать по схеме
На данный момент застрял на том, что фрагмент открывается методом replace по верх другого xthtp FragmentTransaction. При этом он именно наслаивается, и фрагмент по верх которого он наслоился активен("Лайфхак" с укажи фон у фрагмента который наслоился, помогает только визуально перекрыть фрагмент, но не устраняет, то что первый фрагмент еще активен и по нему можно кликнуть и открыть другой элемент списка) Пытаюсь так же сделать toolBar в Activity, что бы из фрагмента с детальной информацией об элементе recycleView можно было вернуться в recycleview кнопкой назад. По этому разместил его в именно activity, что бы в случае с большим экраном(Планшет) можно было разместить два фрагмента на одном экране.
Проект залит на git ветка navigation. Может кто сталкивался с таким и может чем помочь.
P.S.Ссылку на гит убрал в итоге. Google и подобные статьи здесь конкретно мне не помогли, возможно я что то на@!ев@#тил, что то. Так же, если есть другой более правильный способ выполнить данную задачу, то буду благодарен за посвящение. Ибо только начал разбираться с данной темой и пока что очень плохо в ней ориентируюсь. Так же любой code review Приветствуется) Просто встречал только те примеры где реализуется только часть подобных задач или используют 2-3 activyty в одном собственно список а в другом детализация.
Код ActivityMain
public class MainActivity extends AppCompatActivity {
private Film film;
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
}
public void replaceFragment(final Fragment fragment, Film film){
if(fragment!= null){
if (fragment instanceof FilmDetailFragment){
toolbar.setTitle(R.string.app_name);
FilmsFragment f1 = new FilmsFragment();
Log.d("MyTag", "if");
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.filmsContainer, f1);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}else if(fragment instanceof FilmsFragment){
Log.d("MyTag", "else if");
toolbar.setTitle(film.getLocalizedName());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
toolbar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
Log.d("MyTag", "setOnClickListener");
}
});
FilmDetailFragment f1 = FilmDetailFragment.newInstance(film);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.filmsContainer, f1);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
else {
toolbar.setTitle("another");
Log.d("MyTag", "another");
}
}else {
toolbar.setTitle("null");
Log.d("MyTag", "null");
}
this.film = film;
}
@Override
public void onBackPressed() {
super.onBackPressed();
Log.d("MyTag", "Click home toolbar");
}
}
XML Activity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
tools:context=".MainActivity">
<include
layout="@layout/tool_bar"
android:id="@+id/toolBar"></include>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/toolBar"
android:id="@+id/filmsContainer">
<fragment
android:name="com.example.films.fragments.FilmsFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="@layout/films_fragment" />
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Код фрагмента списка
public class FilmsFragment extends Fragment {
private RecyclerView recyclerView;
private FilmAdapter filmAdapter;
private GridLayoutManager gridLayoutManager;
private List<Film> films;
public FilmsFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
films = new ArrayList<>();
View view = inflater.inflate(
R.layout.films_fragment, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.filmsRecycler) ;
if (recyclerView.getParent() != null){
((ViewGroup)recyclerView.getParent()).removeView(recyclerView);
}
gridLayoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(gridLayoutManager);
filmAdapter = new FilmAdapter(films, getContext());
recyclerView.setAdapter(filmAdapter);
RetrofitClient.getInstance().getApi().getFilms().enqueue(new Callback<Films>() {
@Override
public void onResponse(Call<Films> call, Response<Films> response) {
if (response.body() != null) {
films.addAll(response.body().getFilms());
recyclerView.getAdapter().notifyDataSetChanged();
}
}
@Override
public void onFailure(Call<Films> call, Throwable t) {
Toast toast = Toast.makeText(getContext(), R.string.toast_text, Toast.LENGTH_SHORT);
toast.show();
}
});
filmAdapter.setListener(new FilmAdapter.Listener() {
public void onClick(int position) {
((MainActivity)getActivity()).replaceFragment(FilmsFragment.this, films.get(position));
}
});
return recyclerView;
}
}
XML Фрагмента списка
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/filmsRecycler"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
Код фрагмента самого фильма
public class FilmDetailFragment extends Fragment {
private static final String ARG_PARAM1 = "film";
private Film mParam1;
public FilmDetailFragment() {
// Required empty public constructor
}
public static FilmDetailFragment newInstance(Film film) {
FilmDetailFragment fragment = new FilmDetailFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_PARAM1, film);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getParcelable(ARG_PARAM1);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_detail_films, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ImageView imageView = getActivity().findViewById(R.id.imageView) ;
Glide.with(getContext())
.load(mParam1.getImageUrl())
.error(Glide.with(imageView)
.load(R.drawable.nothing))
.into(imageView);
}
}
XML фрагмента самого фильма
<androidx.constraintlayout.widget.ConstraintLayout
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"
tools:context=".fragments.FilmDetailFragment">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>