简单来说就是利用接口来实现,具体看代码。
public class MyFragment extends Fragment {
public interface FragmentListener {
public void doSomething();
}
@Override
public void onAttach(Activity activity) {
FragmentListener fragmentListener = (FragmentListener) activity;
fragmentListener.doSomething();
super.onAttach(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.myfragment, container, false);
return view;
}
}
复制代码
MyActivity.java
public class MainActivity extends Activity implements FragmentListener {
public final static String FRAGMENT_TAG = "fragment tag";
TextView text_activity = null;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_activity = (TextView) MainActivity.this
.findViewById(R.id.text_activity);
text_activity.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fManager = getFragmentManager();
MyFragment fragment = (MyFragment) fManager
.findFragmentById(R.id.group);
if (fragment == null) {
FragmentTransaction fTransaction = fManager
.beginTransaction();
fTransaction
.add(R.id.group, new MyFragment(), FRAGMENT_TAG);
fTransaction.commit();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void doSomething() {
TextView textView = (TextView) MainActivity.this
.findViewById(R.id.text_activity);
textView.setText("Fragment与activity之间的通信就放在Fragment的回调接口FragmentListener中,让Activity去实现这个接口,使Fragment相对于Activity更加独立");
}
}