Фрагмент замены Android по-прежнему отображает часть замещенного фрагмента
У меня есть вкладка, которая содержит линейный макет с поиском и списком. Когда пользователь нажимает один из результатов поиска, я хочу заменить этот макет на другой макет, содержащий детали выбора.
Что происходит, когда я заменяю фрагмент поиска, заменяется только часть списка вида макета; поиск будет по-прежнему видимым и активным на экране.
Вот мой макет поиска:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/search_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<SearchView
android:id="@+id/public_calendar_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:iconifiedByDefault="false"
</SearchView>
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1.0"
android:choiceMode="singleChoice" />
<TextView
android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:gravity="center"/>
</LinearLayout>
Вот макет детали:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/detail_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="vertical" >
<Space
android:layout_width="0dip"
android:layout_height="20dip"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="horizontal" >
<Space
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".1" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".8"
android:text="@string/label_Name" />
<Space
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".1" />
</LinearLayout>
.........
</LinearLayout>
И мой код для замены фрагмента поиска:
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack.
DetailFragment fragment = DetailFragment.newInstance(cal);
transaction.replace(R.id.search_layout, fragment);
transaction.addToBackStack(null);
transaction.commit();
Создание фрагмента детали:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.detail_layout, container, false);
return v;
}
static DetailFragment newInstance(String cal) {
DetailFragment d = new DetailFragment();
return d;
}
Что я делаю неправильно? Как я могу заменить весь макет поиска.
Спасибо!
Ответы
Ответ 1
Я понял свою проблему. Марко был не совсем прав, но он указал мне в правильном направлении.
Проблема заключалась в том, что идентификатор контейнера, который я передавал методу replace, был идентификатором фрагмента, который я заменял, а не идентификатором контейнера фрагмента. Это, по-видимому, объясняет, почему некоторые из исходных элементов управления фрагментами оставались после замены - весь фрагмент не заменялся.
Я изменил его, чтобы получить идентификатор вида контейнера фрагмента, и это сработало! Здесь код:
transaction.replace(((ViewGroup)(getView().getParent())).getId(), fragment);
Я нашел ответ для получения идентификатора вида контейнера здесь Получить идентификатор контейнера фрагмента.
Ответ 2
Я использовал правильный идентификатор, а затем он не уходил. Оказывается, вам нужно установить Background color
на необходимый цвет в новом макете фрагмента, например.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/white_color">
Ответ 3
Чтобы решить эту проблему, установите для свойства android: background значение "? android: windowBackground" в файлах макета фрагмента.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?android:windowBackground"
tools:context=".MainFragment">
...
</LinearLayout>
В Fragment_2
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?android:windowBackground"
tools:context=".SomeFragment">
...
</LinearLayout>