How to add a button in a Fragment?

How to add a button or textView inside a Fragment from Activity

  • I see lot of questions, but the flow what I was looking was not achieved. Basically, I have a simple Activity Class, inside which I am attaching a Fragment. Now, if I try to addView as in below code snippet FragmentManager fragmentManager = getFragmentManager(); fragmentTransaction = fragmentManager.beginTransaction(); hello = SimpleFragment.newInstance("hello","helloo"); fragmentTransaction.add(R.id.main, hello, "Fragment"); ViewGroup vg = ((ViewGroup)fragmentManager.findFragmentById(R.id.fragment).getView()); fragmentTransaction.commit(); vg is returning null, because, inside the fragment class, the onCreateView() is not yet reached. So My question is how do I know from Activity if fragment view is ready and when I should addViews to the fragment

  • Answer:

    I have achieved similar things in the past using ViewTreeeObservers. I was seeing the same issue as you with null view references. This was for programmatically adding new child views to a parent view, rather than working with fragment groups, but the same principle may work for you. if (actionButtionPanel.getHeight() == 0) { ViewTreeObserver actionButtonPanelObserver = actionButtionPanel.getViewTreeObserver(); actionButtonPanelObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { ViewTreeObserver obs = getView().findViewById(R.id.llExamDetailInteractionBar).getViewTreeObserver(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { obs.removeOnGlobalLayoutListener(this); } else { obs.removeGlobalOnLayoutListener(this); } addActionButtons(); } }); } else { addActionButtons(); } This checks for the panel (the parent view) not yet being laid out and so it has 0 height, it then registers an observer which is triggered when the view is laid out and calls my function to add child views. You can see this source in context here: https://github.com/o0rebelious0o/IC2014_ExICS_Android_App/blob/master/ExICS/src/main/java/rce10/ic/ac/uk/exics/Fragments/ExamDetailFragment.java

mobdev999 at Stack Overflow Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.