【问题标题】:Android fragments - findFragmentByTag always returns nullAndroid 片段 - findFragmentByTag 始终返回 null
【发布时间】:2013-08-20 09:25:08
【问题描述】:

我环顾四周,发现了几个类似主题的问题,但对我的情况没有任何帮助。 我正在尝试使用 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);
}

}

我在这里做错了什么? 干杯, 最大

【问题讨论】:

  • 你确定 savedInstanceState 是 null 吗?
  • ft.addToBackStack(F_SETTINGS);

标签: android android-fragments android-support-library


【解决方案1】:

在您的代码中,您没有在替换方法中提到标记所以,
使用fragment的replace方法的这种结构

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

有关更多信息,请参阅此链接。 fragment replace with tag name

【讨论】:

  • 天哪,你不会相信我盯着代码看了多长时间才发现问题所在...谢谢,现在可以使用了。
  • 请看我的相关问题:stackoverflow.com/questions/24833912/…
  • 非常感谢兄弟。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-03
  • 1970-01-01
  • 2017-12-22
  • 2018-07-14
  • 1970-01-01
相关资源
最近更新 更多