android-fragments 我如何在Android中显示工具栏后退按钮片段?

xdnvmnnf  于 2022-11-14  发布在  Android
关注(0)|答案(2)|浏览(186)

我在一个Android应用程序上工作,我有三个片段,我想显示片段工具栏上的后退按钮,以返回到以前的片段,现在我如何才能实现这一点??我是Android新手,请指导我。

public class SecondFragment extends Fragment {


Button button2;
private PageViewModel viewModel;
EditText editTextName, editTextEmail, editTextDesc;
public SecondFragment() {
    // Required empty public constructor
}


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view =  inflater.inflate(R.layout.fragment_second, container, false);
    button2 = view.findViewById(R.id.next2);
    editTextName = view.findViewById(R.id.edittextName);
    editTextEmail =  view.findViewById(R.id.edditextEmail);
    editTextDesc = view.findViewById(R.id.edittexDesc);
    viewModel = new ViewModelProvider(requireActivity()).get(PageViewModel.class);
    

    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (editTextName.getText().toString().isEmpty() || editTextEmail.getText().toString().isEmpty() || editTextDesc.getText().toString().isEmpty())
            {

                editTextName.setError("Enter name");
                editTextEmail.setError("Enter Email");
                editTextDesc.setError("Enter Description");

            }else {

             //   viewModel.setName(editTextName.getText().toString());
                enterName(editTextName.getText().toString());
                enterEmail(editTextEmail.getText().toString());
                enterDesc(editTextDesc.getText().toString());
              //  viewModel.setEmail(editTextEmail.getText().toString());
              //  viewModel.setDescription(editTextDesc.getText().toString());
                FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                Fragment NAME = new LastFragment();
                fragmentTransaction.replace(R.id.container, NAME);
                fragmentTransaction.commit();
            }
        }
    });

    return view;
}

这是我的代码片段bother我有三个这样的片段我需要添加后退按钮的工具栏上有三个fragemtns

fivyi3re

fivyi3re1#

您可以在Activity中添加一个工具栏,它是这些片段的容器。然后,在片段中,您可以执行以下操作:

private void setupToolbar() {
   YourActivity yourActivity = (YourActivity) getActivity()
   if(yourActivity != null) {
      yourActivity.toolbar.setSkipVisibility(View.GONE) // Or View.VISIBLE
      yourActivity.toolbar.setText() // Set some text
      yourActivity.toolbar.setOnBackButtonClickListener{ yourActivity.onBackPressed() }
   }
}
bxpogfeg

bxpogfeg2#

请按照下面的步骤操作。

fragmentTransaction.replace(R.id.container, NAME);
fragmentTransaction.addToBackStack(null);  //Add this line
fragmentTransaction.commit();

这将解决您的问题。谢谢。

相关问题