2013-08-20 45 views
9

我环顾四周,发现了一些类似主题的问题,但没有任何对我有帮助的问题。 我试图使用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); 
} 

}

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

+1

你确定savedInstanceState为空吗? – njzk2

+1

ft.addToBackStack(F_SETTINGS); <---这不会标记您的片段。 – bofredo

回答

20

在你的代码并没有提及在替代方法,所以
使用片段

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

的替代方法的这种结构请参阅此链接了解更多信息标签。 fragment replace with tag name

+0

哦,亲爱的,你不会相信我盯着代码来弄清楚什么是错的......多亏了,现在就开始工作。 – maxdownunder

+0

请参阅我的相关问题:http://stackoverflow.com/questions/24833912/refresh-fragment-ui-from-fragmentactivity –

相关问题