Android片段 - findFragmentByTag始终返回null

max*_*der 9 android android-fragments android-support-library

我已经浏览了一下并发现了几个类似主题的问题,但在我的案例中没有任何帮助.我正在尝试使用getSupportFragmentManager().findFragmentByTag(TAG)访问现有的活动片段,但它总是返回null.对类似问题的回复表明,执行提交需要一段时间,因此如果过早调用,调用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);
}
Run Code Online (Sandbox Code Playgroud)

}

我在这做错了什么?干杯,马克斯

Pra*_*vin 20

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

ft.replace(R.id.container, newFragment,"fragment_tag_String");
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅此链接.片段替换为标签名称