Bade
Bade

Reputation: 709

Android: Finding dynamically made Fragment

I'm learning Android via http://developer.android.com/training. There's a code to add fragment

getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, article_fragment).commit();

and it works, but I can't do this

ArticleFragment articleFrag = (ArticleFragment)
            getSupportFragmentManager().findFragmentById(R.id.article_fragment);

cause there's no article_fragment in R.java yet. Am I'm missing something or is it bug?

Upvotes: 1

Views: 106

Answers (2)

Yoann Hercouet
Yoann Hercouet

Reputation: 17986

Here is an example using the tags:

First change the way you add the fragment to your activity, for example:

getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, yourArticleFragment, "fragment_tag").commit();

Then just get back the Fragment using the tag "fragment_tag" used as a parameter above:

ArticleFragment yourArticleFragment = (ArticleFragment) fm.findFragmentByTag("fragment_tag");

Upvotes: 1

x90
x90

Reputation: 2170

You should use container id ArticleFragment articleFrag = (ArticleFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container); or find by tag.

Upvotes: 3

Related Questions