Android笔记--Fragment获取父Activity的控件并修改内容demo

1、首先在Activity里动态加载Fragment,

BlankFragment blankFragment = new BlankFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction beginTransaction =   fragmentManager.beginTransaction();
        beginTransaction.add(R.id.fragmentcontent, blankFragment);
        beginTransaction.addToBackStack(null);
        beginTransaction.commit();

2、然后在Fragment里的onAttach()方法中获得Activity的Textview控件的引用,

 @Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
if (activity instanceof MainActivity) {
           MainActivity mainActivity = (MainActivity) activity;
           textView = (TextView) mainActivity.findViewById(R.id.textView);
       }
}

3、最后就可以在Fragment里修改父Activity的TextView控件了。

相关源码下载:http://download.csdn.net/detail/weilexuexia/9623094

也可以利用接口回调实现fragment与activity的通信,相关链接:http://blog.csdn.net/weilexuexia/article/details/50863891

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页