FragmentManager findFragmentByTag在Android 4.0.4和Android 4.4.2上的不同行为

时间:2015-03-18 07:24:55

标签: android fragment fragmentmanager

我对此问题有疑问: https://code.google.com/p/android/issues/detail?id=13252

问题是在更改Android设备的语言时,某些组件(如RadioButton和CheckBox)未更新为新语言。我有两个片段,FragmentA和FragmentB。在我的FragmentActivity中,我添加了FragmentA。从Fragment A中,我添加了FragmentB。我应用了一个解决方法,我调用FragmentA或FragmentB方法将语言显式设置为正确的语言。

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    FragmentManager fm = getSupportFragmentManager();
    if (fm != null) {
	Fragment f = null;
			
	if ((f = fm.findFragmentByTag(FragmentB.TAG)) != null) {
		Log.e(TAG, FragmentB.TAG+ " is visible");
		((FragmentB)f).refreshLocale();
	} else {
		Log.e(TAG, FragmentB.TAG+ " is NOT visible");
	}

	if ((f = fm.findFragmentByTag(FragmentA.TAG)) != null) {
		Log.e(TAG, FragmentA.TAG+ " is visible");
		((FragmentA)f).refreshLocale();
        } else {
                Log.e(TAG, FragmentA.TAG+ " is NOT visible");
	}
    }
}

我上面所做的是在恢复Activity时通过TAG查找Fragments,然后调用每个Fragment中的refreshLocale()方法,以便应用正确的语言。修复工作正常,但是在我的两个测试设备中存在行为不一致的情况。

在我的Galaxy S5(4.4.2)中,使用变通方法更新FragmentA和FragmentB的语言。但对于我的Xperia Mini Pro(4.0.4),只有FragmentB(当前可见的片段)会更新。我把Logs放在我的代码中,我发现FragmentA和FragmentB实际上都是可见的,我的代码到达FragmentA的refreshLocale()方法,但不知怎的,文本仍未更新为新语言。

refreshLocale()方法的示例:

public void refreshLocale() {
    if (m_recallValues != null) {
        m_recallValues.setText(R.string.recall_values);
    }

    if (m_recallValuesRun != null) {
        m_recallValuesRun.setText(R.string.recall_run);
    }
}

关于这个问题的任何想法? 谢谢。

1 个答案:

答案 0 :(得分:0)

那是因为你试图找到片段B的FragmentManager无法找到所述片段。片段B是从片段A开始的,因此使用了孩子FragmentManager。您应该使用片段A中的getChildFragmentManager()代替。

这可能有所帮助:儿童FragmentManager