通过片段传递数据

时间:2018-08-02 09:41:16

标签: java android android-studio android-fragments fragment

我的应用很简单,只是我有一个 FragmentA FragmentB ,第一个有一个按钮,通过第二个片段传递字符串数据(“嗨,我是A”),有文字显示此消息我的问题是

为什么我的“ ModifyTxt”方法不起作用?

public class newFragmentA extends Fragment{
    Button button;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.newfragmenta_layout,container,false);
    }

    newFragmentB newfragmentB;
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        button = getActivity().findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                newfragmentB.ModifyTxT("Hi I'm A");
            }
        });


       }
}

这是我的第二个Fragment(FragmentB)

public class newFragmentB extends Fragment {
    TextView textView;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.newfragmentb_layout,container,false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        textView = getActivity().findViewById(R.id.TV);
    }
    public void ModifyTxT(String string){
        textView.setText(string); }
}

2 个答案:

答案 0 :(得分:0)

尝试一下:

public class FragmentB extends Fragment {
  // ...

  public static FragmentB newInstance() {
        return new FragmentB();
    }
}

在FragmentA中:

button.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    FragmentB newFragment = FragmentB.newInstance();
    newFragment.modifyTxT("Hi I'm A");
  }
});

请谨慎编写规则:类名的大写首字母,方法的小写首字母...

答案 1 :(得分:0)

喜欢使用界面与Fragments

进行通信
public class FragmentA extends Fragment{
    public interface MyCallback{
        void modifyTxT(String text); // method naming convention start with small letter.
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        button = getActivity().findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (newfragmentB instanceof MyCallback) {
                    ((MyCallback)newfragmentB).modifyTxT("Hi I'm A");
                }
            }
        });


    }

}

public  class FragmentB extends Fragment implements FragmentA.MyCallback{

    public static FragmentB getInstance(){
        return new FragmentB();

    }

    @Override
    public void modifyTxT() {

    }
}