首页 > 解决方案 > 从一个片段移动到另一个片段时,片段 UI 不可见

问题描述

我正在尝试从现有片段移动到另一个片段。事务已成功完成,但没有可见的 ui 元素。

<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:id="@+id/mainLinearLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
tools:context=".Main.Main"></LinearLayout>

要跳转到第二个片段 onclick -

case R.id.homeElectronicsLinearLayout:
            Fragment fragmentElectronics = new Electronicss();
            if(getActivity().getSupportFragmentManager()!=null){
                getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.mainLinearLayout,fragmentElectronics).hide(Main.this).addToBackStack(null).commit();

            }
            break;

第二个片段 -

public class Electronicss extends Fragment{

private RecyclerView twentyFourHoursDealsRecyclerView,justLaunchedRecyclerView,bestOfElectronicsRecyclerView;
private String featuredCategoryKey="featured";

public Electronicss() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_electronicss, container, false);

    // Inflate the layout for this fragment
    return view;
}}

第二个片段 ui 仅包含一个按钮,但仍然不可见:-

<android.support.constraint.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"
android:scrollbars="vertical"
tools:context=".Categories.Electronics.Electronicss">

<Button
    android:id="@+id/button11"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

标签: androidxmlandroid-layoutandroid-fragments

解决方案


除了添加片段使用替换之外,还将您的 LinearLayout 更改为 FrameLayout,作为要替换的片段的容器。

注意:如果您不想将片段存储在堆栈中,只需删除 addToBackStack() 行。

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, yourfragment)
                .addToBackStack(null)
                .commit();

推荐阅读