要点:
- Fragment中定义内部接口和方法;
- Activity继承该接口,并实现该接口的方法(方法中处理Fragment传过来的数据);
- Fragment中获得Activity对象,并调用接口中方法。
- 核心思想:接口的回调
效果图:
源码:
1、自定义的fragment布局文件fragment.xml
<?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="wrap_content"
android:orientation="vertical" >
<EditText
android:id="@+id/et1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送到Activity" />
</LinearLayout>
2、fragment源码
public class myFragment extends Fragment {
private EditText et01;
private Button btn01;
public sendDataToActivity mySendDataToActivity;
// 定义一个内部接口,接口中方法用于处理发送给activity的数据
public interface sendDataToActivity {
public void send(String str);
}
/*
* fragment生命周期中,onAttach在与activity关联后,首先执行, 并且,在这里会返回一个activity对象,
* 获得activity后,即可用于后面调用activity中方法
*/
@Override
public void onAttach(Activity activity) {
mySendDataToActivity = (sendDataToActivity) activity;
super.onAttach(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
et01 = (EditText) view.findViewById(R.id.et1);
btn01 = (Button) view.findViewById(R.id.btn);
btn01.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 调用activity中实现的接口方法
mySendDataToActivity.send(et01.getText().toString());
}
});
return view;
}
}
3、MainActivity的布局文件activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/layout"
tools:context=".MainActivity" >
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#ff0000"
android:text="Activity接收到来自fragment的信息为:"
android:id="@+id/tv1" />
</LinearLayout>
4、MainActivity
//继承接口
public class MainActivity extends Activity implements sendDataToActivity {
private TextView tv01;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv01 = (TextView) findViewById(R.id.tv1);
// 实例化自定义的fragment
myFragment fragment = new myFragment();
// 后面和动态加载fragment一样
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction beginTransaction = fragmentManager
.beginTransaction();
// 将fragment添加到activity的布局中
beginTransaction.add(R.id.layout, fragment);
beginTransaction.addToBackStack(null);
beginTransaction.commit();
}
//实现接口中方法,并处理fragment传过来的数据
@Override
public void send(String str) {
tv01.setText(tv01.getText().toString()+str);
}
}