简体   繁体   English

Android 目标片段未出现在导航中

[英]Android Destination Fragment not Appearing on Navigation

I'm trying to use a navigation graph to navigate between two fragments.我正在尝试使用导航图在两个片段之间导航。 For some reason, when I call the navigate method with the graph's generated action, the destination fragment is being "created" but not appearing, while the start fragment just sits as if it's been inactivated but doesn't go away.出于某种原因,当我使用图形生成的操作调用导航方法时,目标片段正在“创建”但没有出现,而起始片段就好像它已被停用但没有消失一样。 I think I've followed all the steps listed on Google's documentation page for this , but I am probably missing something simple!我想我已经按照谷歌文档页面上列出的所有步骤进行了操作,但我可能遗漏了一些简单的东西!

Here are my dependencies:这是我的依赖项:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    // ViewModel and LiveData
    def lifecycle_version = "2.1.0"
    implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"

    def nav_version = "2.1.0"
    implementation "androidx.navigation:navigation-fragment:$nav_version"
    implementation "androidx.navigation:navigation-ui:$nav_version"

    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

MainActivity主要活动

In my main activity class, I'm just defining a ModelView in OnCreate() :在我的主要活动类中,我只是在OnCreate()定义了一个ModelView

public class MainActivity extends AppCompatActivity {
    MealDataModel mealDataModel;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Create the model on create of the main activity
        mealDataModel = ViewModelProviders.of(this).get(MealDataModel.class);
    }
}

And in my main activity layout, I'm just using the NavHostFragment:在我的主要活动布局中,我只使用了 NavHostFragment:

...
<fragment
        android:id="@+id/fragment2"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/nav_graph" />
...

Navigation Graph导航图

And here is my navigation graph:这是我的导航图:

<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/nav_graph"
    app:startDestination="@id/mealCostFrag">

    <fragment
        android:id="@+id/mealCostFrag"
        android:name="com.finley.program2.frag.MealCostFrag"
        android:label="fragment_meal_cost"
        tools:layout="@layout/fragment_meal_cost" >
        <action
            android:id="@+id/action_mealCostFrag_to_tipPercentFrag"
            app:destination="@id/tipPercentFrag" />
    </fragment>
    <fragment
        android:id="@+id/tipPercentFrag"
        android:name="com.finley.program2.frag.TipPercentFrag"
        android:label="fragment_tip_percent"
        tools:layout="@layout/fragment_tip_percent" />
</navigation>

Start Fragment开始片段

My start destination of the navigation graph is this fragment...:我导航图的起始目的地是这个片段...:

public class MealCostFrag extends Fragment {
    private MealDataModel mealDataModel;
    private EditText etCost;
    private Button btnNext;
    private double cost;
    public MealCostFrag() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View myView = inflater.inflate(R.layout.fragment_meal_cost, container, false);
        mealDataModel = ViewModelProviders.of(getActivity()).get(MealDataModel.class);

        // Set listeners and such...
        etCost = myView.findViewById(R.id.editText01);
        btnNext= myView.findViewById(R.id.button01);
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    cost = Double.parseDouble(etCost.getText().toString());
                    if (cost <= 0) throw new Exception();
                    mealDataModel.setMealCost(cost);
                    Log.i("COST FRAG","Navigating to tip pct with cost = " + mealDataModel.getMealCost());
                    Navigation.findNavController(v).navigate(R.id.action_mealCostFrag_to_tipPercentFrag);
                } catch (Exception e) {
                    Log.e("COST FRAG", "Invalid cost entered, cost = " + cost);
                    Toast.makeText(getContext(),
                            "Please enter a valid meal cost.", Toast.LENGTH_SHORT).show();
                }
            }
        });
        return myView;

    }

}

With this layout:有了这个布局:

<?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=".frag.MealCostFrag">

    <EditText
        android:id="@+id/editText01"
        android:layout_width="0dp"
        android:layout_height="55dp"
        android:layout_marginStart="64dp"
        android:layout_marginLeft="64dp"
        android:layout_marginTop="48dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:ems="10"
        android:gravity="center_horizontal|center_vertical"
        android:hint="Cost"
        android:inputType="number|numberDecimal"
        android:textSize="24sp"
        app:layout_constraintEnd_toStartOf="@+id/button01"
        app:layout_constraintHorizontal_bias="1.0"/>

    <Button
        android:id="@+id/button01"
        android:layout_width="87dp"
        android:layout_height="46dp"
        android:layout_marginEnd="64dp"
        android:layout_marginRight="64dp"
        android:text="Next"
        app:layout_constraintBaseline_toBaselineOf="@+id/editText01"
        app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Destination fragment:目标片段:

Here's the fragment I'm trying to navigate to is this, with an empty layout:这是我试图导航到的片段是这样的,布局为空:

public class TipPercentFrag extends Fragment {
    private MealDataModel mealDataModel;
    public TipPercentFrag() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View myView = inflater.inflate(R.layout.fragment_meal_cost, container, false);
        mealDataModel = ViewModelProviders.of(getActivity()).get(MealDataModel.class);

        // Set listeners and such...
        Log.i("TIP PCT FRAG", "CreateView of tip pct frag called");

        return myView;

    }
}

What I find peculiar about this is the logs from inside the destination fragment's 'onCreateView()' method are being output, but it is just not displaying.我发现这方面的奇特之处在于正在输出目标片段的“onCreateView()”方法内部的日志,但它只是没有显示。

I know I've provided a massive wall of code for all of you to sift through, so I will be extra appreciative to anybody willing to spend some time helping me out.我知道我已经为大家提供了大量代码供大家筛选,因此我将特别感谢愿意花一些时间帮助我的任何人。 I will provide any extra necessary info upon request.我会根据要求提供任何额外的必要信息。 Thank you all in advance, and hopefully it's a comically trivial error I'm making!提前谢谢大家,希望这是我犯的一个可笑的微不足道的错误!

Just as I suspected, I was making a very simple mistake.正如我所怀疑的那样,我犯了一个非常简单的错误。 The view I was inflating on my destination fragment was the view of my start fragment.我在目标片段上膨胀的视图是我的开始片段的视图。 Just a copy and paste error.只是一个复制和粘贴错误。

This:这个:

// Inflate the layout for this fragment
        View myView = inflater.inflate(R.layout.fragment_meal_cost, container, false);
        mealDataModel = ViewModelProviders.of(getActivity()).get(MealDataModel.class);

Just needed to be this:只需要是这样的:

// Inflate the layout for this fragment
        View myView = inflater.inflate(R.layout.fragment_tip_percent, container, false);
        mealDataModel = ViewModelProviders.of(getActivity()).get(MealDataModel.class);

The lesson learned here is to closely examine every step of the process when debugging!这里学到的教训是在调试时仔细检查过程的每一步! Errors do typically hide in plain sight.错误通常隐藏在显而易见的地方。

If you are using DataBinding please change inflater lines these lines如果您正在使用数据绑定,请更改充气线这些线

from

mDataBinding=DataBindingUtil.inflate(getLayoutInflater(),R.layout.fragment_date_sheet, container, false);

to

mDataBinding= DataBindingUtil.inflate(inflater,R.layout.fragment_date_sheet, container, false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM