Android碎片 - findFragmentByTag总是返回null

9
我看了一下,发现有几个与该主题类似的问题,但没有一个能帮到我。 我正在尝试使用 getSupportFragmentManager().findFragmentByTag(TAG) 访问现有的活动片段,但它总是返回null。类似问题的回复建议等待提交被执行一段时间后才调用 findFragmentByTag,如果调用太早就会返回 null。我尝试了两件事情:
  • 在提交后立即添加 getSupportFragmentManager().executePendingTransactions()
    但仍然得到null
  • 添加了一个按钮...在活动创建后按下此按钮, 注册片段并显示视图应该给系统留出足够的时间来提交。但我仍然得到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);
}

在这里我做错了什么? 谢谢, Max


1
你确定savedInstanceState是空的吗? - njzk2
1
ft.addToBackStack(F_SETTINGS); <--- 这不会为您的片段打标签。 - bofredo
1个回答

22

在你的代码中,你没有在替换方法中提到标签。因此,请使用此分段替换方法的结构。

ft.replace(R.id.container, newFragment,"fragment_tag_String");

请参考此链接获取更多信息。 替换片段并附上标签名


哦,亲爱的,你不会相信我盯着代码看了多久才弄清楚问题...谢谢,现在可以工作了。 - maxdownunder
请查看我的相关问题:http://stackoverflow.com/questions/24833912/refresh-fragment-ui-from-fragmentactivity - Dr.jacky
非常感谢你,兄弟。 - Akshay kumar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接