步骤
1、fragment中定义接口,并设置数据
2、activity实现接口
示例:
FragmentA :发送方
public class FragmentA extends Fragment {
private EditText et;
private FragmentACallBack fragmentACallBack;
public interface FragmentACallBack {
void setData(String data);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
fragmentACallBack = (FragmentACallBack) getActivity();
}
@Nullable
@Override
public View
onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_a, container,
false);
et = (EditText) view.findViewById(R.id.et);
Button bt = (Button) view.findViewById(R.id.bt);
bt.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
fragmentACallBack.setData(et.getText().toString());
}
});
return view;
}
}
布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00ff00"
android:gravity="center"
android:orientation="vertical">
<EditText
android:id="@+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp" />
<Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送"
android:textSize="30sp" />
</LinearLayout>
MainActivityII :接收方
public class MainActivityII extends FragmentActivity implements FragmentA.FragmentACallBack {
private FragmentA fragmentA;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainii);
fragmentA =
new FragmentA();
getFragmentManager().beginTransaction().replace(R.id.container_a, fragmentA,
"fragmentA").commit();
}
@Override
public void setData(String data) {
}
}
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/container_a"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@color/colorAccent"
android:orientation="horizontal" />
</LinearLayout>