Fragment和Activity通信
1.接口方法
最好的方法无非就是通过接口.这样就可以避免不修改的问题.
2.例子:
A.接口的定义
public interface OnViewPagerSelected
{
void onSelected(int position);
}
B.Activity的实现接口
public class FuliQiLinActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener, OnViewPagerSelected
{
OnViewPagerSelected mOnViewPagerSelected;
@Override
public void onAttachFragment(android.support.v4.app.Fragment fragment)
{
mOnViewPagerSelected = (OnViewPagerSelected)fragment;
super.onAttachFragment(fragment);
}
/**
* 自定义接口,Fragment-> Activity
*
* @param position
*/
@Override
public void onSelected(int position)
{
}
}
C.Fragment 的实现
public class QiLinFragment extends Fragment implements OnViewPagerSelected
{
OnViewPagerSelected mOnViewPagerSelected;
@Override
public void onAttach(Activity activity)
{
mOnViewPagerSelected = (OnViewPagerSelected)activity;
super.onAttach(activity);
}
/**
*Activity -> Fragment
*/
@Override
public void onSelected(int position)
{
Log.e("taggg", "" + position);
}
}