导航抽屉活动:在片段之间传递值

huangapple go评论61阅读模式
英文:

Navigation Drawer Activity: passing values between fragment

问题

以下是翻译好的内容:

我有一个问题,我无法将一个String值从一个Fragment传递到另一个Fragment

这是我代码的一部分:

FragmentA

public class HomeFragment extends Fragment {
    
    private HomeViewModel homeViewModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                ViewModelProviders.of(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);

        Button btn = (Button) root.findViewById(R.id.myButton);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GalleryFragment galleryFragment = new GalleryFragment();
                Bundle bundle = new Bundle();
                String s = "ciao";
                bundle.putString("Data", s);
                galleryFragment.setArguments(bundle);
                Toast.makeText(getActivity(),s,Toast.LENGTH_LONG).show(); //通过这个我知道函数是正常的
            }
        });
        return root;
    }
}

FragmentB

public class GalleryFragment extends Fragment {

    private GalleryViewModel galleryViewModel;
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        galleryViewModel =
                ViewModelProviders.of(this).get(GalleryViewModel.class);
        View root = inflater.inflate(R.layout.fragment_gallery, container, false);

        Bundle bundle = getActivity().getIntent().getExtras();
        TextView textView = (TextView) root.findViewById(R.id.myTitleText);
        if(bundle!=null){
            String name = bundle.getString("Data");
            Toast.makeText(getActivity(),name,Toast.LENGTH_LONG).show();
            textView.setText(name);
        }
        return root;
    }
}

如果我删除if(bundle!=null)部分,调试器会报错:

java.lang.NullPointerException: 尝试调用空对象引用上的 'java.lang.String android.os.Bundle.getString(java.lang.String)' 方法

总结:

我在fragmentA --> 我点击按钮 --> 我移动到fragmentB来查看TextView是否已更改值 --> 什么也没发生。

有人能解释一下错误是什么吗?

谢谢你的时间。

英文:

I have a problem, I can't pass a String value from a Fragment to another Fragment.

This is a part of my code:

The FragmentA:

public class HomeFragment extends Fragment {

private HomeViewModel homeViewModel;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    homeViewModel =
            ViewModelProviders.of(this).get(HomeViewModel.class);
    View root = inflater.inflate(R.layout.fragment_home, container, false);

    Button btn = (Button) root.findViewById(R.id.myButton);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            GalleryFragment galleryFragment = new GalleryFragment();
            Bundle bundle = new Bundle();
            String s = "ciao";
            bundle.putString("Data", s);
            galleryFragment.setArguments(bundle);
            Toast.makeText(getActivity(),s,Toast.LENGTH_LONG).show(); //with this i know the function is ok
        }
    });
    return root;
}
}

The FragmentB:

public class GalleryFragment extends Fragment {

private GalleryViewModel galleryViewModel;
public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    galleryViewModel =
            ViewModelProviders.of(this).get(GalleryViewModel.class);
    View root = inflater.inflate(R.layout.fragment_gallery, container, false);

    Bundle bundle = getActivity().getIntent().getExtras();
    TextView textView = (TextView) root.findViewById(R.id.myTitleText);
    if(bundle!=null){
        String name = bundle.getString("Data");
        Toast.makeText(getActivity(),name,Toast.LENGTH_LONG).show();
        textView.setText(name);
    }
    return root;
}
}

If I delete the if(bundle!=null) part, the debugger give me this error:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference

SUMMARY:

I am on fragmentA --> I click the button --> I move to fragmentB to see if the TextView has changed value --> nothing happened.

Can someone explain me what is the error?

Thank you for your time.

答案1

得分: 0

你应该了解一下 ViewModel:ViewModel 概述

你应该在父活动中初始化一个 ViewModel,然后在每个片段被创建时,提供对该共用 ViewModel 的访问。

这样,这三个组件将共同访问一个共享的生命周期感知对象,你可以用它来进行轻松的互相通信。

英文:

You should look into ViewModel: ViewModel Overview.

You should initialize a ViewModel in your parent activity and then when each Fragment is created, provide access to that common ViewModel.

All 3 components will then have shared access to a common lifecycle-conscious object that you can use for easy intercommunication.

答案2

得分: 0

这是解决方案 -_-,我不知道为什么之前不起作用。

FragmentA 内的 onClick 方法中,在末尾粘贴以下内容:

FragmentTransaction transaction = getFragmentManager().beginTransaction();

transaction.replace(R.id.nav_host_fragment, galleryFragment);
transaction.addToBackStack(null);

transaction.commit();

我发布这个供需要的人使用。

英文:

this is the solution -_-, I dont know why before didnt work.

Inside of FragmentA in the onClick method, paste this at the end:

            FragmentTransaction transaction = getFragmentManager().beginTransaction();

            transaction.replace(R.id.nav_host_fragment, galleryFragment);
            transaction.addToBackStack(null);

            transaction.commit();

I post this for who need it

huangapple
  • 本文由 发表于 2020年5月3日 22:52:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/61576502.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定