在Fragment中的Activity——startActivityForResult与onActivityResult

来源:互联网 发布:马云淘宝初期如何推广 编辑:程序博客网 时间:2024/06/05 00:38
fragmanager = this.getSupportFragmentManager();FragmentTransaction transaction = fragmanager.beginTransaction();tabHost = new FragMapOList();transaction.add(R.id.fragment_map_list, tabHost, "f1");transaction.show(tabHost);transaction.commit();
tabHost继承了Fragment类
在onCreateView方法中做了如下处理
Intent mapIntent = new Intent();View btnmap = mInflater.inflate(R.layout.frag_btn_map_layout, null);mapIntent.setClass(getActivity(), MapActivity.class);Intent listIntent = new Intent();View btnlist = mInflater.inflate(R.layout.frag_btn_list_layout, null);listIntent.setClass(getActivity(), DSListActivity.class);host.addTab(host.newTabSpec("tab1").setIndicator(btnmap).setContent(mapIntent));host.addTab(host.newTabSpec("tab2").setIndicator(btnlist).setContent(listIntent));

那么问题来了,如果我在MapActivity中用startActivityForResult(MapActivity.this, xxx.class)方法,并且在这某某activity中setResult了,然后再在其中用onActivityResult能接收到吗?
并不能!
那么在Fragment或是父Activity中用onActivityResult呢?
然并卵!
可选择通过startActivityForResult(MapActivity.this.getParent(), xxx.class),让后在父Activity中用onActivityResult来做相应处理。
那么如果是activity.sendBroadcast(intent);发送广播和接收广播呢?
我们先看看host.newTabSpec("tab1").setIndicator(btnmap).setContent(mapIntent)做了什么
方法newTabSpec实例化了一个内部类TabSpec,其方法setContent
/** * Specify an intent to use to launch an activity as the tab content. */public TabSpec setContent(Intent intent) {    mContentStrategy = new IntentContentStrategy(mTag, intent);    return this;}
其中new IntentContentStrategy(mTag, intent)实例化另一个内部类,我们在切换tab1和tab2的时候,这个类的getContentView()方法将被调用并返回View,其中
mLocalActivityManager.startActivity(mTag, mIntent)只是用主线程对象装载了Activity,并没有启动;所以最后就相当于放了个View进到tab中而已,这就解
释了上面onActivityResult为什么没反应。那么广播究竟可不可以在其中被接收呢?你自己可以尝试一下。
public View getContentView() {    if (mLocalActivityManager == null) {        throw new IllegalStateException("Did you forget to call 'public void setup(LocalActivityManager activityGroup)'?");    }    final Window w = mLocalActivityManager.startActivity(            mTag, mIntent);    final View wd = w != null ? w.getDecorView() : null;    if (mLaunchedView != wd && mLaunchedView != null) {        if (mLaunchedView.getParent() != null) {            mTabContent.removeView(mLaunchedView);        }    }    mLaunchedView = wd;    // XXX Set FOCUS_AFTER_DESCENDANTS on embedded activities for now so they can get    // focus if none of their children have it. They need focus to be able to    // display menu items.    //    // Replace this with something better when Bug 628886 is fixed...    //    if (mLaunchedView != null) {        mLaunchedView.setVisibility(View.VISIBLE);        mLaunchedView.setFocusableInTouchMode(true);        ((ViewGroup) mLaunchedView).setDescendantFocusability(                FOCUS_AFTER_DESCENDANTS);    }    return mLaunchedView;}

阅读全文
0 0
原创粉丝点击