Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragments and Activities -- where do I put my application logic?

I have created my view how I want it to look. It has 1 images, an input box, and a button. I will want to load another activity when the button is clicked. I am confused why there are fragments and activities. I am new to the Android world (coming from iOS).

My understanding is that Activities are similar to ViewControllers, but I am not sure I understand what a fragment is.

Where do I put the event handling?

package com.phppointofsale.phppointofsale;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;

public class StoreUrlActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_url);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new StoreUrlFragement()).commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.store_url, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class StoreUrlFragement extends Fragment {

        public StoreUrlFragement() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_store_url,
                    container, false);
            return rootView;
        }
    }

}
like image 990
Chris Muench Avatar asked Mar 10 '14 02:03

Chris Muench


People also ask

Is it better to use fragments or activities?

Activities are an ideal place to put global elements around your app's user interface, such as a navigation drawer. Conversely, fragments are better suited to define and manage the UI of a single screen or portion of a screen. Consider an app that responds to various screen sizes.

How do you put a fragment inside an activity?

Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.

Why is it useful to have fragments in your app?

According to the Android documentation, a fragment is a part of applications user interface that is bound to an activity. Fragments have their lifecycle and layouts or UI components. Fragments help enrich your UI design, pass data between different screens, and adapt to different device configurations.


1 Answers

Firstly I would recommend reading this Fragments . Pay particular attention to the created fragment section, which includes the fragment life-cycle diagram. Second download and compile this Sample App,the effective navigation app will help you understand how different fragments work in tandem, and even implements a action bar.

To answer your question more or less a fragment can be thought of as a separate class. Once you call upon that particular fragment you can call functions from within that class.

Fragment Case-Switch

This is some sample code to show you what I mean.

 public Fragment getItem(int i){
    switch (i) {
        case 0:
            // The first section of the app is the most interesting -- it offers
            // a launchpad into the other demonstrations in this example application.
            return new LaunchpadSectionFragment();

        case 1:
            return new BluetoothClass();
      
        default:
            // The GPS section of the app .
            Fragment fragment = new DummySectionFragment();
            Bundle args = new Bundle();
            args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
            fragment.setArguments(args);
            return fragment;
        }
}

In this case each fragment for me represented a class, which was implemented in a separate tab and each tab had a separate functionality. One of the key advantages of fragments is you can run separate activities without first letting one activity complete.

Furthermore each fragment is an extension of the java.lang.Object library. So it has all those functions + additional ones. I would read this as well. Lastly it would be a good idea to have separate xml files for each fragment then you can display that separately when a fragment is invoked.

Some more code

Each fragment will/could have this

public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
            // Do stuff on creation. This is usually where you add the bulk of your code. Like clickListners

        View rootview = inflater.inflate(R.layout.xml_the_fragment_uses container,false);
        rootview.findViewById(R.id.your_id).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Do something 
        }
    });
}
            
    
    public void onStart(){
        super.onStart();
        Toast.makeText(getActivity(), "Fragment started",Toast.LENGTH_SHORT).show();
    }       

    public void onResume(){
        super.onStart();
        Toast.makeText(getActivity(), "Fragment Resumed",Toast.LENGTH_SHORT).show();
                
    }
    
    public void onStop(){
        super.onStart();
        Toast.makeText(getActivity(), "Fragment Stoped",Toast.LENGTH_SHORT).show();
        disableBT();
    }

Remember these functions are from the fragment life-cycle I mentioned earlier.

Hopefully that gave you some idea on fragments. Also remember to read this as a lot of functionality uses the v7 app compat library. Including the fragment manager.

like image 157
SeahawksRdaBest Avatar answered Oct 20 '22 13:10

SeahawksRdaBest