2016-02-08 4 views
0

Это мой основной XMLЗаменить фрагмент и удалить старый фрагмент

<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/fragment_place" android:layout_width="wrap_content" android:layout_height="fill_parent"/> 

Это мой Основная деятельность

protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    FragmentManager fm = getFragmentManager(); 
    FragmentTransaction fragmentTransaction = fm.beginTransaction(); 
    fragmentTransaction.add(R.id.fragment_place, new ThirdClass()); 
    fragmentTransaction.commit(); 
} 

Это ThirdClass

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    View v = inflater.inflate(R.layout.test_fragment1, container, false); 
    FragmentManager fm = getFragmentManager(); 
    FragmentTransaction fragmentTransaction = fm.beginTransaction(); 
    fragmentTransaction.add(R.id.fragment_place, new FourthClass()); 
    fragmentTransaction.commit(); 
    return v; 
} 

Это расположение ThirdClass

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"><TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Second Fragment"/></LinearLayout> 

Это FourthClass

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    View v = inflater.inflate(R.layout.test_frag, container, false); 
    return v; 
} 

И раскладка

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"><TextView android:layout_width=" android:layout_height=" android:text="Third Fragment"/></LinearLayout> 

Мой вопрос заключается в том, что эти фрагменты были сохранены не сменяют друг друга, и это показывает мне это. enter image description here

+0

Почему вы делаете операции фрагмента внутри onCreateView() фрагмента? Независимо от того, используйте replace() вместо add() ... –

+0

Я делаю транзакции только для тестирования, замена работает, спасибо! Но есть ли фрагмент «позади» последний, который все еще активен, это плохо для приложения? Спасибо. – ASTeam

ответ

3

Использование fragmentTransaction.replace() вместо fragmentTransaction.add()

От the documentation:

Заменить существующий фрагмент, который был добавлен в контейнер. Это , по существу, то же самое, что и вызов remove (Fragment) для всех в настоящее время добавлены фрагменты, которые были добавлены с помощью того же containerViewId, а затем add (int, Fragment, String) с теми же аргументами, приведенными здесь.

Смежные вопросы