Ho dato un'occhiata in giro e ho trovato un paio di domande con un argomento simile, ma nel mio caso nulla ha aiutato. Sto tentando di accedere a un frammento attivo esistente utilizzando getSupportFragmentManager(). FindFragmentByTag (TAG), ma restituisce sempre null. Le risposte a domande simili suggerivano che ci voleva un po 'prima che il commit fosse eseguito, quindi chiamare findFragmentByTag restituirebbe null se chiamato troppo presto. Ho provato due cose:I frammenti di Android - findFragmentByTag restituisce sempre null
- aggiungono getSupportFragmentManager() executePendingTransactions()
subito dopo il commit, ma ancora ottenere nulla.. - aggiunto un pulsante ... premendo questo dopo che l'attività è stata creata, il frammento registrato e la vista visualizzata dovrebbe lasciare il sistema tempo sufficiente per il commit. Ma ottengo ancora null.
Ecco la mia attività:
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);
}
}
che cosa sto facendo male qui? Cheers, Max
sei sicuro savedInstanceState è nullo? – njzk2
ft.addToBackStack (F_SETTINGS); <--- questo non codifica i tuoi frammenti. – bofredo