Android-如何在onActivityResult()之后返回当前片段? [英] Android - How can i return the current fragment after onActivityResult()?
问题描述
我有一个活动,其中包含一些按钮和一些片段.
I have an activity that have some buttons and some fragments.
如果我单击按钮A,我将显示片段"FragA".在"FragA"中时,我可以执行一些操作,例如从图库中选择图片,选择图片后我需要留在"FragA"中.
If I click on button A, i'll show Fragment "FragA". When I'm in "FragA", I can perform some actions like choose a picture from gallery and I need to stay in "FragA" after choose picture.
但是当我选择图片时,我返回到活动"并且"FragA"被隐藏.
But when I choose picture, I return to Activity and "FragA" is hidden.
如何执行一个动作并且仍在同一片段中或在活动"中显示正确的片段?
How can perform an action and still in same Fragment or display correct fragment in Activity?
推荐答案
您可以重新创建片段,并使用以下代码的修改将其替换为活动"中的片段:
You can recreate fragment again and replace it in your Activity with using modification of this code:
if (currentState == STATE_MAIN_FRAGMENT) {
return;
}
mainScreenFragment = (MainScreenFragment) getSupportFragmentManager().findFragmentByTag(MainScreenFragment.TAG);
if (mainScreenFragment == null) {
mainScreenFragment = new MainScreenFragment();
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.flFragmentContainer, mainScreenFragment, MainScreenFragment.TAG);
fragmentTransaction.commit();
第一个"if"检查是否设置了片段.这不是必需的,但这是一个好习惯.它可以防止您在不需要时替换片段.
First "if" checks if the fragment is set or not. It is not required but it's a good practice. It prevents you from replacing fragment when it is not necessary.
对我来说,有一件事很奇怪.因为您说的是<<"FragA"是隐藏的>>,-这意味着它已被设置但容器不可见?然后yourFragmentContainer.setVisiblity(View.VISIBLE);在活动"结果中.
And there is one thing strange for me. Because you said <<"FragA" is hidden>> - that means it was already set but container is not visible? Then yourFragmentContainer.setVisiblity(View.VISIBLE); in on Activity result.
最后一个可以帮助您的事情是保留该片段,以使它永远不会被破坏并再次创建.一些有用的链接:
And the last thing that could help you is to retain the fragment so it won't be ever destroyed and recreated again. Some helpful links:
了解片段的setRetainInstance(boolean)
http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)
或者您也可以只复制粘贴Button的OnClickListener中的内容,使其也发生在onActivityResult上.
Or you can just copy-paste what is in your Button's OnClickListener so it happens onActivityResult too.
这篇关于Android-如何在onActivityResult()之后返回当前片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!