Fragment调用Activity里的数据
在Activity中创建Bundle数据包,并调用Fragment的setArguments(Bundle bundle)方法,此方法在上面的代码中已经介绍了。Activity调用Fragment里的数据
在Fragment中定义一个内部回调接口,让包含该Fragment的Activity实现该回调接口,这样Fragment可调用该回调方法将数据传递给Activity。下面主要实现在Activity调用Fragment的数据。先在Fragment中定义一个内部回调接口:
public interface OnFragmentInteractionListener { public void onFragmentInteraction(String uri); }
在Fragment的onAttach()方法中将Activity转换为OnFragmentInteractionListener接口:
@Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } }
private OnFragmentInteractionListener mListener; if (mListener != null) {
mListener.onFragmentInteraction("需要传递给Activity的值");
宿主Activity则需要实现此接口,并重写onFragmentInteraction(String uri)方法,这样就实现了数据从Fragment到Activity的传递:
public class MainActivity extends ActionBarActivity implements Image1Fragment.OnFragmentInteractionListener
@Override
public void onFragmentInteraction(String uri) {
TextView tv=(TextView)findViewById(R.id.tt);
tv.setText(uri);
}
7.效果截图