将数据从活动传递到片段Android Studio

时间:2019-01-27 02:28:30

标签: android-studio android-activity fragment

-这是我的片段:-

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_save, container, false);


    savedAlamat = view.findViewById(R.id.saved_alamat);
    savedContac = view.findViewById(R.id.saved_kontak);
    savedName = view.findViewById(R.id.saved_nama);


    String malamat = getArguments().getString("mAlamat");
    String mcontac = getArguments().getString("mContac");
    String mname = getArguments().getString("mname");

    savedAlamat.setText(malamat);
    savedContac.setText(mcontac);
    savedName.setText(mname);


    return view;
}

//并且这是constarin框架布局的主要功能:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_save, container, false);


    savedAlamat = view.findViewById(R.id.saved_alamat);
    savedContac = view.findViewById(R.id.saved_kontak);
    savedName = view.findViewById(R.id.saved_nama);


    String malamat = getArguments().getString("mAlamat");
    String mcontac = getArguments().getString("mContac");
    String mname = getArguments().getString("mname");

    savedAlamat.setText(malamat);
    savedContac.setText(mcontac);
    savedName.setText(mname);


    return view;
}

-我不明白为什么我总是获取NotNULLobject,我想在该活动和片段之间传递数据。

1 个答案:

答案 0 :(得分:1)

在“活动”中,编写此代码

  Bundle bundle = new Bundle(); 
  bundle.putString("mAlamat", "Data to send"); // set Fragmentclass Arguments 
  Fragmentclass fragobj = new Fragmentclass(); 
  fragobj.setArguments(bundle);

在Fragment类中,接收像这样的数据

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("mAlamat");    
    return inflater.inflate(R.layout.fragment, container, false);
}

Courtesy