碎片没有显示



我对碎片是新手。我在我的主活动中有一个BroadcastReceiver,我从一个baseadapter调用它,并使用此代码显示片段,但从未显示!

BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Fragment frag = new NewviewFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(frag, "nav_newview");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();

}
};

这是我的碎片的代码

package com.example.myapp.ui.newview;
public class NewviewFragment extends Fragment {

public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container,Bundle savedInstanceState) {
newviewViewModel =
new ViewModelProvider(this).get(NewviewViewModel.class);
root = inflater.inflate(R.layout.fragment_newview, container, false);

newviewViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
//    textView.setText(s);
}
});
return root;
}

}

这是我的fragment_newview.xml

<?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=".ui.newview.NewviewFragment">

<WebView
android:id="@+id/webview1"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
/>

</androidx.constraintlayout.widget.ConstraintLayout>

感谢您的帮助!

当您使用导航架构组件库时,不应该使用FragmentTransaction手动进行碎片事务。

您可以通过NavController进行交易

BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
NavController controller = Navigation.findNavController(MainActivity.this, R.id.nav_host_fragment);  // R.id.nav_host_fragment is the id of the placeholder fragment in content_main.xml
controller.navigate(R.id.nav_newview);           
}
};

我假设您的主要活动命名为MainActivity&CCD_ 5被托管在该活动中。

更新:

我没有注意到你制作了一个渐变动画,带有导航组件。为了有一些动画:

navController.navigate(R.id.secondFragment, null, getNavOptions());
NavOptions getNavOptions() {
return new NavOptions.Builder()
.setEnterAnim(R.anim.fragment_open_enter)
.setExitAnim(R.anim.nav_default_exit_anim)
.setPopEnterAnim(R.anim.nav_default_pop_enter_anim)
.setPopExitAnim(R.anim.nav_default_pop_exit_anim)
.build();
}

并在res/anim中创建您喜欢的动画

您也可以在mobile_navigation.xml 中执行此操作

最新更新