getSupportFragmentManager()。findFragmentByTag在旋转后返回不同的实例

时间:2017-06-01 14:04:10

标签: java android

我知道如果我旋转设备,当前的活动会被破坏并重新创建。如果活动的onCreate()中有Html code: input type="text" class="form-control" id="tokenfield-typeahead" value="red,green,blue" /> script: var engine = new Bloodhound({ local: [{value: 'red'}, {value: 'blue'}, {value: 'green'} , {value: 'yellow'}, {value: 'violet'}, {value: 'brown'}, {value: 'purple'}, {value: 'black'}, {value: 'white'}], datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.value); }, queryTokenizer: Bloodhound.tokenizers.whitespace }); engine.initialize(); $('#tokenfield-typeahead').tokenfield({ typeahead: [null, { source: engine.ttAdapter() }] }); 可用,我可以通过调用

来避免创建新的片段
savedInstanceState

然而@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { iMyFragment = new MyFragment() Log.d(TAG, "____ onCreate: iMyFragment: " + iMyFragment); } else { iLottoTicketFragment = (LottoTicketFragment) getSupportFragmentManager().findFragmentByTag(MyFragment.FRAGMENT_TAG); Log.d(TAG, "____ savedinstance: iMyFragment: " + iLottoTicketFragment); if(iMyFragment == null) { iMyFragment = new MyFragment(); Log.d(TAG, "____ recreate: iMyFragment: " + iLottoTicketFragment); } } } 返回的实例与之前的实例不同,会造成各种麻烦。

这是日志输出(比较ids 973eb65和73e27ce)

findFragmentByTag

任何人都知道如何从06-01 15:47:16.687 15729-15729/D/MainActivity: ____ onCreate: iMyFragment: MyFragment{973eb65} 06-01 15:47:29.774 15729-15729/D/MainActivity: ____ savedinstance: iMyFragment: MyFragment{73e27ce #1 id=0x7f0f0098 MyFragment} 获取完全相同的实例?

1 个答案:

答案 0 :(得分:0)

旋转设备时,会创建一个新活动。保留了状态,但重新创建了所有视图和片段。