Fragment 通信

来源:互联网 发布:写歌的软件 编辑:程序博客网 时间:2024/06/06 09:14
#### 3.通信   (不常用)

1.在activity中创建Fragment的对象

package com.example.asus.fragment;import android.app.Activity;import android.app.FragmentManager;import android.app.FragmentTransaction;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;/** * Created by ASUS on 2017/5/21. */public class ThirdActivity extends Activity {    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.fragment3);        Button button = (Button) findViewById(R.id.send);        button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                EditText text = (EditText) findViewById(R.id.text2);                String content = text.getText().toString();                Bundle bundle = new Bundle();                bundle.putString("name", content);                MyFragment3 fragment3=new MyFragment3();                fragment3.setArguments(bundle);                /*FragmentManager fragmentManager=getFragmentManager();                FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();                fragmentTransaction.add(R.id.frame ,fragment3, "fragment");                fragmentTransaction.commit();*/                Toast.makeText(ThirdActivity.this,"向Fragment发送数据"+text.getText(),Toast.LENGTH_LONG).show();            }        });    }}



2.在Fragment中接收数据

public class MyFragment3 extends Fragment {    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.data, container, false);        TextView textView = (TextView) view.findViewById(R.id.text);        String text=getArguments().get("name")+"";        textView.setText(text);        Toast.makeText(getActivity(),"已经成功接收数据"+text,Toast.LENGTH_SHORT).show();        return  view;    }}

其中data的布局如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="match_parent">    <EditText        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:id="@+id/text1"        />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/send"        android:text="发送"/>    <TextView        android:layout_width="match_parent"        android:layout_height="fill_parent"        android:id="@+id/text2"        android:textSize="20dp"        />    </LinearLayout>

原创粉丝点击