Question

I have app where it's only a timer with a whole bunch of special methods in the main activity. This works great with no problems. Now, that I have it working, I'm trying to include it in a much more complicated application where I'm going to be inserting the timer in numerous places via fragments.

Should I include all of my special methods in my fragment activity? IE:

public class Timer_fragment extends android.support.v4.app.Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.timer_frag, container, false);
    }
    //SHOULD I insert my special methods here?
}

or should I include them in my main?

I'm asking because I've tried both ways, and the fragment activity way gave me errors in java, but putting them in my main gave me errors during runtime. Basically I have a timer that runs great as a standalone application, but I'm trying to convert it into a fragment, so that I can plug it into multiple places in my app.

Examples of "special methods": I take a view in the layout and update it according to the new numbers inputted on the timer. These methods require the view to be inflated before they can be used.

Note: The errors at runtime I am experiencing are nullPointerExceptions.

Was it helpful?

Solution

The idea behind a Fragment is that it is a resuable section (ie fragment) of an Activity that can be used in other Activities, or even in the same Activity but with the addition or absence of other Fragments.

In the Gmail app for example, the list of all emails in an inbox is one Fragment, and the actual contents of an email is another Fragment. On a tablet in landscape mode, both are shown. A phone in portrait mode, however, will only show one of the two Fragments at once.

Thus each Fragment should encapsulate all functionality and UI components necessary to use that Fragment. This means that all of your "special" methods such as inflating the Fragment's view XML should happen within the Fragment.

The Activity (or Activities) that utilize the Fragment should only need to use a FragmentManager (or similar method) to add your Fragment to the Activity's layout. The parent Activity of a Fragment should also handle communication between Fragments and other components such as other Activities, Fragments, or Threads.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top