【安卓学习笔记】Activity与Fragment通信——Activity发送到Fragment

要点:

  • activity中,实例化fragment,并通过fragment的setArguments方法,向fragment发送bundle绑定的数据;
  • fragment中,通过getArguments方法接收activity发送过来的数据。

具体代码:

1、MainActivity的布局文件activity_main.xml


    
    
    

2、MainActivity

public class MainActivity extends Activity {

    private EditText et01;
    private Button btn01;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et01 = (EditText) findViewById(R.id.et1);
        btn01 = (Button) findViewById(R.id.btn);

        btn01.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                // 实例化自定义的fragment
                myFragment fragment = new myFragment();
                // 通过bundle绑定数据,fragment的setArguments方法传值
                Bundle bundle = new Bundle();
                bundle.putString("tag", et01.getText().toString());
                fragment.setArguments(bundle);

                // 后面和动态加载fragment一样
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction beginTransaction = fragmentManager
                        .beginTransaction();
                // 将fragment添加到activity的布局中
                beginTransaction.add(R.id.layout, fragment);
                beginTransaction.addToBackStack(null);
                beginTransaction.commit();
            }
        });
    }
}

3、fragment布局文件fragment.xml




    


4、自定义的Fragment

public class myFragment extends Fragment {

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

        View view = inflater.inflate(R.layout.fragment, container, false);
        TextView tv = (TextView) view.findViewById(R.id.text);

        // 获取activity发送来的数据
        Bundle bundle = getArguments();
        String value = bundle.getString("tag");
        tv.setText("接收到的值 为:" + value);
        return view;
    }
}

你可能感兴趣的:(【安卓学习笔记】Activity与Fragment通信——Activity发送到Fragment)