我环顾四周,发现了一些类似主题的问题,但没有任何对我有帮助的问题。 我试图使用getSupportFragmentManager()。findFragmentByTag(TAG)访问现有的活动片段,但它始终返回null。类似问题的回复表明,执行提交需要一段时间,因此如果调用过早,调用findFragmentByTag将返回null。我已经试过两件事情:Android碎片 - findFragmentByTag总是返回null
- 添加getSupportFragmentManager()executePendingTransactions()后
立即提交,但仍得到空。 - 添加了一个按钮...在创建活动后按此按钮, 已注册的片段和显示的视图应该使 系统有足够的时间提交。但我仍然得到null。
这里是我的活动:
public class MainActivity extends ActionBarActivity {
private static final String F_SETTINGS = "f_settings";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
debug();
}
});
if (savedInstanceState == null) {
FSettings newFragment = new FSettings();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, newFragment);
ft.addToBackStack(F_SETTINGS);
ft.commit();
// getSupportFragmentManager().executePendingTransactions();
//// Activating this did not make any difference...
}
debug();
}
private void debug() {
String txt = "null";
Fragment frag = getSupportFragmentManager().findFragmentByTag(F_SETTINGS);
if (frag != null) {
txt = frag.toString();
}
Log.i("Testing", txt);
}
}
什么我错在这里做什么? 干杯, 最大
你确定savedInstanceState为空吗? – njzk2
ft.addToBackStack(F_SETTINGS); <---这不会标记您的片段。 – bofredo