关于Android开发中,Activity 向 Fragment传递数据的两种方式。

activity与fragment之间进行数据传递是,在Activity中将要传递的数据封装在一Bundle中,使用setArgument(Bundel bundel)方法传递数据,在要传递到的Fragment中 使用this.getArgment(),得到传递到的Bundle。下面分别说明两种方法:

第一种方法:

Main_activity中的布局:




    

FrameLayout用于动态的更新fragment。

Activity:

public class MainActivity extends AppCompatActivity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button =(Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FirstFragment fragment = new FirstFragment();
                Bundle bundle = new Bundle();
                bundle.putString("data","传递到的数据");
                fragment.setArguments(bundle);//数据传递到fragment中
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.framelayout,fragment);
                fragmentTransaction.commit();
            }
        });

    }

}

replace方法的第二个参数不能使用new 类名();这样数据是不能传递的。

Fragment:

public class FirstFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_first,container,false);
        TextView textView = (TextView)view.findViewById(R.id.textview);
        Bundle bundle =this.getArguments();//得到从Activity传来的数据
        String mess = null;
        if(bundle!=null){
            mess = bundle.getString("data");
        }
        textView.setText(mess);
        return view;
    }
}

这样一来当按下Button的时候,碎片回加载进Framelayout中,并且bundle中的数据也会传递到fragment的textview中。第一中方法很简单,但是实现起来可能有一些麻烦,下面我们新建一个Fragment:

public class BlankFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener; 

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BlankFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BlankFragment newInstance(String param1, String param2) {
        BlankFragment fragment = new BlankFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_blank, container, false);
        TextView textView = view.findViewById(R.id.textview);
        Bundle bundle =getArguments();
        String message = null;
        if(bundle!=null){
            message = bundle.getString(ARG_PARAM1);
        }
        textView.setText(message);
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {

            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

在这个类中发现一个newInstance的静态方法,仔细看这个方法似乎可以用来将数据传递到fragment中。

重新定义MainActivity:

public class MainActivity extends AppCompatActivity implements BlankFragment.OnFragmentInteractionListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button =(Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BlankFragment blankFragment = BlankFragment.newInstance("传递来的数据1","传递来的数据2");
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.framelayout,blankFragment);
                fragmentTransaction.commit();
            }
        });

    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }
}
activity中必须实现fragment类中的内部接口,然后我们见直接定义一个BlankFragment就可以直接不是局传递过去啦·,在onCreateView中接收数据就行啦,我这里只接收到一个数据。结果一样可以运行。


关于Android开发中,Activity 向 Fragment传递数据的两种方式。_第1张图片

关于Android开发中,Activity 向 Fragment传递数据的两种方式。_第2张图片


你可能感兴趣的:(关于Android开发中,Activity 向 Fragment传递数据的两种方式。)