Fragment Flavors

  • Replies:0
  • OpenNot stickiedUnanswered
  • Forum posts: 1

Mar 13, 2017 8:22:16 AM via Website

Hi guys.
I'm struggling with my question on treehouse.Here is the question:
"I created a new fragment to store our news items. It's called When I went to add a constructor to pass in the selected index, Android Studio told me that I shouldn't do that.
Can you please help me by using a bundle to pass the index to my new NewsItemFragment when it is selected? (I added a constant key for the index in "
and this is the code is like:

public class MainActivity extends AppCompatActivity implements NewsFragment.NewsListener {
// New tags for referring to fragments
public static final String NEWS_FRAGMENT = "news_fragment";
public static final String NEWSITEM_FRAGMENT = "newsitem_fragment";

public void onCreate(Bundle savedInstanceState) {

    FragmentManager fragmentManager = getFragmentManager();

    NewsFragment savedFragment = (NewsFragment) fragmentManager.findFragmentById(;

    if (savedFragment == null) {
        NewsFragment newsFragment = new NewsFragment();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(, newsFragment);


public void onNewsItemSelected(int index) {
    NewsItemFragment fragment = new NewsItemFragment();
    // TODO: how do we pass arguments to the new Fragment?

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(, fragment);


public class NewsItemFragment extends Fragment {
public static final String KEY_NEWS_ITEM_INDEX = "news_item_index";

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // TODO:  Hmmm, how do we get this index?
    int index = 0;
    View view = inflater.inflate(R.layout.fragment_newsitem, container, false);
    return view;

  Fragment fragment = new Fragment(); // replace your custom fragment class 

Bundle bundle = new Bundle();

           bundle.putInt("index", index); // use as per your need


public void onStop() {


public class News {
public static String[] headlines = new String[]{
"Treehouse student develops #1 App in Google App Store",
"Oracle and Google decide to hug it out",
"Java8 coming to Android! Is it too late?"

Please Help!