Итак, я делаю это для целей обучения,
Что именно я хочу сделать:
Создать два фрагмента. Первый фрагмент имеет кнопку, которая при нажатии заменяет фрагмент.основное действие со вторым фрагментом, второй фрагмент просто содержит текстовое представление, говорящее «Это второй фрагмент», но когда я пытался это сделать, первый фрагмент загружается два раза и при нажатии кнопки первый экземпляр остается там, где второй экземплярпоменял на второй фрагмент.Ребята, скажите, что я делаю не так: (я прилагаю код, а также снимки экрана)
MainActivity.java:
package com.femindharamshi.fragmenttrials;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements FirstFragment.OnFragmentInteractionListener {
FragmentTransaction fragmentTransaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
FirstFragment newFrament = new FirstFragment();
fragmentTransaction.add(R.id.fragmentView, newFrament);
fragmentTransaction.commit();
}
@Override
public void onFragmentInteraction() {
Toast.makeText(this, "Button in fragment pressed!", Toast.LENGTH_SHORT).show();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
SecondFragment newFragment = new SecondFragment();
fragmentTransaction.replace(R.id.fragmentView, newFragment);
fragmentTransaction.commit();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
<fragment
android:id="@+id/fragmentView"
android:name="com.femindharamshi.fragmenttrials.FirstFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"/>
</RelativeLayout>
FirstFragment.java
package com.femindharamshi.fragmenttrials;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class FirstFragment extends Fragment {
private OnFragmentInteractionListener mListener;
Button button;
public FirstFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);
button = view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onButtonPressed();
}
});
return view;
}
public void onButtonPressed() {
if (mListener != null) {
mListener.onFragmentInteraction();
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction();
}
}
SecondFragment.java
package com.femindharamshi.fragmenttrials;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SecondFragment extends Fragment {
public SecondFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_second, container, false);
}
@Override
public void onDetach() {
super.onDetach();
}
}
Проблема: Также без упоминания android:name="com.femindharamshi.fragmenttrials.FirstFragment"
в основномактивность, приложение вылетает.Что если я не хочу загружать фрагмент в начале действия, почему я должен упомянуть об этом?и даже если я загружу secondFragment в этом, это нормально?хотя в названии написано FirstFragment?
Что если я не хочу назначать основной вид деятельности с классом фрагмента перед рукой и хочу сделать это программно?
Снимки экрана: