Autore Topic: Tutorial sui fragments  (Letto 802 volte)

Offline nick091

  • Nuovo arrivato
  • *
  • Post: 3
  • Respect: 0
    • Mostra profilo
  • Dispositivo Android:
    Nexus 7
  • Sistema operativo:
    Ubuntu 10.04 Lucid
Tutorial sui fragments
« il: 09 Maggio 2013, 08:37:05 CEST »
Ciao a tutti
è da un paio di settimane che mi sono dedicato ad android ed ho ho seguito il tutorial Building a Dynamic UI with Fragments | Android Developers
Per capire meglio il codice l'ho modificato introducendo un metodo isDoubleFragmentLayout() con cui mi sono svincolato dalla gestione standard di large/xlarge/land ecc... ed ho leggermante modificato l'interfaccia di comunicazione tra fragment e controller

funziona uguale all'originale per cui lo posto qua

LAYOUT LARGO STATICO /res/layout/main_layout_double.xml
Codice (XML): [Seleziona]
<LinearLayout xmlns:android=""
    <fragment android:name="com.nick.example.ipsum10.HeadlinesFragment"
             android:layout_height="match_parent" />

    <fragment android:name="com.nick.example.ipsum10.ArticleFragment"
             android:layout_height="match_parent" />


LAYOUT STRETTO DINAMICO /res/layout/main_layout_mono.xml
Codice (XML): [Seleziona]
<FrameLayout xmlns:android=""
   android:layout_height="match_parent" />

LAYOUT ARTICOLO /res/article_view.xml
Codice (XML): [Seleziona]
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android=""
   android:layout_height="fill_parent" >

       android:textSize="18sp" />


Codice (Java): [Seleziona]
package com.nick.example.ipsum10;

import android.content.res.Configuration;
import android.os.Bundle;

public class Ipsum10MainActivity extends FragmentActivity
    implements HeadlinesFragment.HeadlinesController {

        protected void onCreate(Bundle savedInstanceState) {
                /* in /res ci sono due definizioni del layout "main_layout_double" per tablet e main_layout_mono per handset
                 * il layout per handset é un "FrameLayout" adatto a contenere un fragment alla volta, quello large
                 * è un LinearLayout in cui mettiamo due fragments
                 * */

            // layout version with the fragment_container FrameLayout, we must add the first fragment

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {

            // Create an instance of HeadlinesFragment
            HeadlinesFragment firstFragment = new HeadlinesFragment();

            // In case this activity was started with special instructions from an Intent,
            // pass the Intent's extras to the fragment as arguments

            // Add the fragment to the 'fragment_container' FrameLayout
                    .add(, firstFragment).commit();

        public boolean isDoubleFragmentLayout() {

//              DisplayMetrics metrics = new DisplayMetrics();
//              Display display = getWindowManager().getDefaultDisplay();
//              display.getMetrics(metrics);
//              int widthDp = (int) (metrics.widthPixels * 160f / metrics.xdpi);
//              int heightDp = (int) (metrics.heightPixels * 160f / metrics.ydpi);
//              float density = metrics.density;
//              int densityDpi = metrics.densityDpi;
//              int heightPixels = metrics.heightPixels;
//              float scaledDensity = metrics.scaledDensity;
//              int widthPixels = metrics.widthPixels;
//              float xdpi = metrics.xdpi;
//              float ydpi = metrics.ydpi;
//              int rotation = display.getRotation();

                boolean isLandscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
//              boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;

                boolean result = isLandscape;
                return result;

    public void onArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment

        // Capture the article fragment from the activity layout
        ArticleFragment articleFrag = (ArticleFragment)

            // Simply call a method in the existing ArticleFragment to update its content

        } else {
            // If we're in the one-pane layout the frag is not available, and must swap frags...

                // Create fragment and give it an argument for the selected article
            ArticleFragment newFragment = new ArticleFragment();
            Bundle args = new Bundle();
            args.putInt(ArticleFragment.ARG_POSITION, position);

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(, newFragment);

Codice (Java): [Seleziona]
package com.nick.example.ipsum10;

import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class HeadlinesFragment extends ListFragment{
    HeadlinesController mCallback;

    // The container Activity must implement this interface so the frag can deliver messages
    public interface HeadlinesController {
        /** Called by HeadlinesFragment when a list item is selected */
        public void onArticleSelected(int position);
                public boolean isDoubleFragmentLayout();

    public void onCreate(Bundle savedInstanceState) {

        // We need to use a different list item layout for devices older than Honeycomb
        int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
                android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

        // Create an array adapter for the list view, using the Ipsum headlines array
        setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));

    public void onStart() {

        // When in two-pane layout, set the listview to highlight the selected list item
        // (We do this during onStart because at the point the listview is available.)
        if (mCallback.isDoubleFragmentLayout()) {


    public void onAttach(Activity activity) {

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception.
        try {
            mCallback = (HeadlinesController) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");

    public void onListItemClick(ListView l, View v, int position, long id) {
        // Notify the parent activity of selected item
        // Set the item as checked to be highlighted when in two-pane layout
//        getListView().setItemChecked(position, true);

Codice (Java): [Seleziona]
package com.nick.example.ipsum10;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class ArticleFragment extends Fragment {
        // la position va ricevuta ed anche mantenuta nel ciclo di vita del fragment
    final static String ARG_POSITION = "position";      // un identificativo per identificare il valore
    int mCurrentPosition = -1;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

        // If activity recreated (such as from screen rotate), restore
        // the previous article selection set by onSaveInstanceState().
        // This is primarily necessary when in the two-pane layout.
        if (savedInstanceState != null) {
            mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.article_view, container, false);

    public void onStart() {

        // During startup, check if there are arguments passed to the fragment.
        // onStart is a good place to do this because the layout has already been
        // applied to the fragment at this point so we can safely call the method
        // below that sets the article text.
        Bundle args = getArguments();
        if (args != null) {
            // Set article based on argument passed in
        } else if (mCurrentPosition != -1) {
            // Set article based on saved instance state defined during onCreateView

    public void updateArticleView(int position) {
        TextView article = (TextView) getActivity().findViewById(;
        mCurrentPosition = position;

    public void onSaveInstanceState(Bundle outState) {

        // Save the current article selection in case we need to recreate the fragment
        outState.putInt(ARG_POSITION, mCurrentPosition);

Codice (Java): [Seleziona]
 * Copyright (C) 2012 The Android Open Source Project
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * See the License for the specific language governing permissions and
 * limitations under the License.

package com.nick.example.ipsum10;

public class Ipsum {

    static String[] Headlines = {
        "Article One",
        "Article Two",
        "Article Three",
        "Article Four"

    static String[] Languages = {

    static String[] Articles = {
        "Article One\n\nAlcuni peraltro definirebbero onomatopee primarie, o vere e proprie, parole che hanno l'unica funzione di evocare l'impressione di un suono e non portatrici di un proprio significato; sono così onomatopee del genere quelle che imitano il verso di un animale, come muuuu o miaoooo, oppure particolari suoni umani come brrr o etciù, ma anche rumori tipici di oggetti o di azioni, come il perepepé della trombetta o il bum della deflagrazione. Deriverebbero poi solitamente da queste, o indirettamente attraverso un processo onomatopeico, delle onomatopee secondarie, o artificiali, che sono invece parole portatrici di un particolare significato: come possono essere i termini che indicano il manifestarsi di un suono: miagolare, abbaiare, ronzare, fruscio, ticchettio, trambusto ecc.",
        "Article Two\n\nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.  Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet",
        "Article Three\n\nIn some cases, you might need a fragment to share events with the activity. A good way to do that is to define a callback interface inside the fragment and require that the host activity implement it. When the activity receives a callback through the interface, it can share the information with other fragments in the layout as necessary.For example, if a news application has two fragments in an activity—one to show a list of articles (fragment A) and another to display an article (fragment B) then fragment A must tell the activity when a list item is selected so that it can tell fragment B to display the article. In this case, the OnArticleSelectedListener interface",
        "Article Four\n\nLa gare de la Bastille était située entre la rue de Lyon et la rue de Charenton, au niveau de la place de la Bastille dont elle tient son nom. La construction de la ligne débute en 1855 en banlieue. L'embarcadère est dessiné par l'architecte François-Alexis Cendrier (qui avait dessiné la gare de Lyon). Elle est inaugurée, de même que le reste de la ligne de chemin de fer, le 22 septembre 1859, en présence de l'empereur Napoléon III. Elle appartient alors à la compagnie de l'Est. Le bâtiment en façade mesure 250 mètres sur 30 mètres de large. Deux nefs abritent quatre voies à quai et deux voies pour la seconde. Compte tenu de l'exiguïté des installations, un pont roulant"
« Ultima modifica: 09 Maggio 2013, 11:34:23 CEST da nick091 »