Ir al contenido principal

Android - Basic Steps (Fragments)

Fragments

  • This functionality allows to support multiple UI panes / User behavior at the same time
  • A fragment is part of an Activity
  • Multiple Fragments can be embedded in an activity to create  a Multi-Pane UI
  • A single fragment can be reused across multiple activities+

Fragment Lyfeclycle States

  • Resumed
    • Is visible in the sunning state
  • Paused
    • Another activity is in the foreground and has focus, containing activity is visible
  • Stopped
    • Fragment is not visible

Fragment Lyfeclycle Methods 

  • onAttach()
    • Fragment is created and attached to the activity
  • onCreate()
    • Initialize the fragment
  • onCreateView
    • Fragments set up &returns its user inferface
  • onActivityCreated
    • activity has completed the onCreate() method and the fragment has been installed
  • onStart()
    • when activity become visible
  • onResume
    • Become visible and ready for user interaction
  • onPause
    • activity is visible without the focus
  • onStop
    • activity is no longer visible
  • onDestroyView
    • the view created in onCreate() method has been detached from the activity 
    • Clean up view resources
  • onDestroy
    • Fragment is no longer in use
    • Clean up fragment resources
  • onDetach
    • null out references to hosting activities

Add a Fragment Statically

  • A fragment layout can be inflated/implemented in OnCreateView
  • OnCreateView return the View at the root of the Fragments's layout, where R.layout.quote_fragment is the fragment's layout 
          return inflater.inflate(R.layout.quote_fragment, container, false);
  • This View is added to the containing activity

Insert two Fragments (Menu -Details)

  • In the activity_main.xml file (the one that is launched) change a Linear Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:orientation="horizontal" 
</LinearLayout>
  • Inside add the Fragments
The first fragment is for the menu       
       <fragment
        android:id="@+id/titles"
        android:layout_width="0px"
        android:layout_height="match_parent"
        android:layout_weight="1"
        class="com.example.myfragmentstatic.Menu" />

The second fragment is for the details

        <fragment
        android:id="@+id/details"
        android:layout_width="0px"
        android:layout_height="match_parent"
        android:layout_weight="2"
        class="com.example.myfragmentstatic.Details" />


  • In the Menu.java
    • Extends from ListFragment
    • Override the mehod onActivityCreated to load the List

@Override
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);

getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
setListAdapter(new ArrayAdapter<String>(getActivity(),
R.layout.title_item, getResources().getStringArray(R.array.Titles) ));
}


R.layout.title_item - Is an XML file named title_item with a TextView as content


<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?android:attr/activatedBackgroundIndicator"
    android:orientation="vertical"
    android:padding="5dip"
    android:textSize="32sp" >

</TextView>



R.array.Titles - Is an array with the menu options defined in the strings.xml file

<string-array name="Titles">
        <item>The Tragedy of Hamlet, Prince of Denmark</item>
        <item>King Lear</item>
        <item>Julius Caesar</item>
    </string-array>

  • Add functionality to show the detail according with the menu option selected
    • Define an Interface
        public interface ListSelectionListener {
public void onListSelection(int index);
}
    • Create a global variable of type ListSelectionListener 
             private ListSelectionListener mListener = null;

    • Override the method onAttach
In this case is getting the father activity and using the interface to interact with the father in a transparent way.

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (ListSelectionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnArticleSelectedListener");
}
}
    • Override the method onListItemClick
Is invoking the father implementation of the method onListItemClick
@Override
public void onListItemClick(ListView l, View v, int pos, long id) {
getListView().setItemChecked(pos, true);
mListener.onListSelection(pos);
}
  • Add the Detail Fragment
    • Create an Array with the options according with each menu in the string.xml file 
    <string-array name="Detail">
        <item>1) Now cracks a noble heart. Good-night, sweet prince; And flights of angels sing thee to thy rest.</item>
        <item>2) As flies to wanton boys, are we to the gods; they kill us for their sport.</item>
        <item>3) There is a tide in the affairs of men, which taken at the flood, leads on to fortune. Omitted, all the voyage of their life is bound in shallows and in miseries.</item>
    </string-array>

    • Create a Layout of type Linear named details_fragment.xml with a TextView inside
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/detailsView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dip"
        android:textSize="32sp" >
    </TextView>

</LinearLayout>
    • In the MainActivity.java
      • Create a global variable to reference to the Details class
private Details mDetails;
      • Override the method onCreate to get the Fragment of the Details, defined in activity_main.xml
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDetails = (Details) getFragmentManager()
.findFragmentById(R.id.details);
}
      • In the MainActivity.java implements ListSelectionListener that is defined in Menu.java and override the method onListSelection to show the proper detail.
@Override
public void onListSelection(int index) {
if (mDetails.getShownIndex() != index) {
mDetails.showQuoteAtIndex(index);
}
}
    • Create a class named Details and extends Fragments
public class Details extends Fragment{

    • Create a global variable to know the index of the detail that is shown and a method to know the index
private int mCurrIdx = -1;
public int getShownIndex() {
return mCurrIdx;
}

    • Override  the method onActivityCreated to get theTextView created in details_fragment.xml and get the array with the texts
Is a  global variable
private TextView mDetailsView = null;      

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mDetailsView = (TextView) getActivity().findViewById(R.id.detailsView);
}
    • Create a method to show the proper detail text.

 public void showQuoteAtIndex(int newIndex) { if (newIndex < 0 || newIndex >= getResources().getStringArray(R.array.Detail).length ) return; mCurrIdx = newIndex; mDetailsView.setText(getResources().getStringArray(R.array.Detail)[mCurrIdx]); }


    • Override the onCreateView method to associated the fragment with the LinearLayout defined in details_fragment.xml

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

Comentarios

Entradas populares de este blog

Python create package

Create a root folder Create a sub-folder "example_pkg" that contains the funtionallity packaging_tutorial/ example_pkg/ __init__.py In the root folder create the following structure  packaging_tutorial/ example_pkg/ __init__.py tests/ setup.py LICENSE README.md in the setup.py contains the configuration of the packages your package is found by find_packages() import setuptools with open ( "README.md" , "r" ) as fh : long_description = fh . read () setuptools . setup ( name = "example-pkg-YOUR-USERNAME-HERE" , # Replace with your own username version = "0.0.1" , author = "Example Author" , author_email = "author@example.com" , description = "A small example package" , long_description = long_description , long_description_content_type = "text/markdown" , url = "https://github.com/pypa/sam...

Rails - Basic Steps III

pValidations Validations are a type of ActiveRecord Validations are defined in our models Implement Validations Go to   root_app/app/models Open files  *.rb for each model Mandatory field validates_presence_of   :field Ex:   validates_presence_of    :title Classes The basic syntax is class MyClass        @global_variable                def my_method              @method_variable        end end Create an instance myInstance = MyClass.new Invoke a mehod mc.my_method class() method returns the type of the object In Ruby, last character of method define the behavior If ends with a question -> return a boolean value If ends with an exclamation -> change the state of the object Getter / Setter method def global_variable       return @global_variable end ...

Android - Basic Steps (Service)

Service Run in the main thread of the hosting application Android can kill the Service if need the resources Purpose Supporting inter-application method execution Performing background processing Start a Service Call Context.startService(Intent intent)\ To call from a Fragment use getActivity().getApplicationContext().startService( intentService); Executing the service After call startService(...)  In the Service is executed the method onStartCommand(...) If the method returns the constant START_NOT_STICKY then Android will not restart the service automatically if the the process is killedp Foreground To execute the service foreground call the method startForeground() Use this if the user is aware of the process Bind to a Service Call the method Context.bindService( Intent service ServiceConnection con int flags ) Send Toast from the Service On the method onStartCommand receive the message   ...