使用导航抽屉在片段之间传递数据的问题

时间:2018-11-10 09:07:47

标签: java android null

我有2个由FeedFragment(片段)组成的片段,它将把字符串转移到Transfer(片段)中。我正在使用接口进行传输。

FeedFragment

 public class FeedFragment extends Fragment {
    public interface OnInputSelected{
        void sendInput(String input);
    }
    public OnInputSelected mOnInputSelected;

    private TextView feed;
    private TextView bt;
    private String input;

    public FeedFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_feed, container, false);
        feed= view.findViewById(R.id.feed);
        bt= view.findViewById(R.id.bt);

        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                input=feed.getText().toString();
                mOnInputSelected.sendInput(input);
            }
        });

        // Inflate the layout for this fragment
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mOnInputSelected = (FeedFragment.OnInputSelected) getTargetFragment();
        } catch (ClassCastException e) {
            Log.e(TAG, "onAttach: ClassCastException : " + e.getMessage());
        }
    }


}

转移

   public class Transfer extends Fragment implements FeedFragment.OnInputSelected{

    public TextView transfer;

    @Override
    public void sendInput(String input) {

        transfer.setText(input);
    }

    public Transfer() {
        // Required empty public constructor
    }

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

        transfer= view.findViewById(R.id.transfer);

        return view;
    }
}

错误

  

尝试在空对象引用上调用接口方法'void com.shrikanthravi.customnavigationdrawer.FeedFragment $ OnInputSelected.sendInput(java.lang.String)'           在com.shrikanthravi.customnavigationdrawer.FeedFragment $ 1.onClick(FeedFragment.java:49)

0 个答案:

没有答案