Example usage for android.view ViewTreeObserver addOnGlobalLayoutListener

List of usage examples for android.view ViewTreeObserver addOnGlobalLayoutListener

Introduction

In this page you can find the example usage for android.view ViewTreeObserver addOnGlobalLayoutListener.

Prototype

public void addOnGlobalLayoutListener(OnGlobalLayoutListener listener) 

Source Link

Document

Register a callback to be invoked when the global layout state or the visibility of views within the view tree changes

Usage

From source file:be.artoria.belfortapp.fragments.MapFragment.java

private void initGUI() {
    /*Setup map and draw route*/
    mapView.setTileSource(TileSourceFactory.MAPQUESTOSM);
    mapView.setBuiltInZoomControls(true);
    final MapController mapCtrl = (MapController) mapView.getController();
    mapCtrl.setZoom(DEFAULT_ZOOM);//from   w w  w.j  a  v a  2 s  .c om
    calculateRoute();
    /*Initially show map*/
    toggleMap(true);

    final Button btnTogglemap = (Button) getView().findViewById(R.id.btnRouteDesc);
    btnTogglemap.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showsMap = !showsMap;
            toggleMap(showsMap);
            if (showsMap) {
                btnTogglemap.setText(getResources().getString(R.string.route_desc));
            } else {
                btnTogglemap.setText(getResources().getString(R.string.show_map));
            }
        }
    });

    final ImageButton btnFullScreen = (ImageButton) getView().findViewById(R.id.btnFullScreen);
    btnFullScreen.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(getActivity(), MapActivity.class);
            getActivity().startActivity(i);
        }
    });

    if (!isFullscreen) {
        btnTogglemap.setVisibility(View.GONE);
    } else {
        btnFullScreen.setVisibility(View.GONE);
    }

    /*Set center of map to current location or Belfry*/
    final ViewTreeObserver vto = mapView.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (firstStart) {
                mapView.getController().setCenter(getCurrentLocation());
                firstStart = false;
            }

        }
    });

    drawMarkers();
}

From source file:de.uulm.graphicalpasswords.openmiba.MIBALoginActivity.java

private void setViews() {
    tableLayout = (TableLayout) findViewById(R.id.tableLayout);
    btnBack = (Button) findViewById(R.id.miba_btnBack);
    btnBack.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            back();//from ww  w. j  a  v  a2  s  .c om
        }
    });

    tvRound = (TextView) this.findViewById(R.id.tvRound);
    tvRound.setText(getString(R.string.label_round) + " 1");

    linlGrid = new LinearLayout[2][4];
    linlGrid[0][0] = (LinearLayout) this.findViewById(R.id.square1);
    linlGrid[1][0] = (LinearLayout) this.findViewById(R.id.square2);
    linlGrid[0][1] = (LinearLayout) this.findViewById(R.id.square3);
    linlGrid[1][1] = (LinearLayout) this.findViewById(R.id.square4);
    linlGrid[0][2] = (LinearLayout) this.findViewById(R.id.square5);
    linlGrid[1][2] = (LinearLayout) this.findViewById(R.id.square6);
    linlGrid[0][3] = (LinearLayout) this.findViewById(R.id.square7);
    linlGrid[1][3] = (LinearLayout) this.findViewById(R.id.square8);

    for (int y = 0; y < 4; y++) {
        for (int x = 0; x < 2; x++) {
            linlGrid[x][y].setBackgroundColor(colors_off[x][y]);
        }

    }

    // get width and height from mainpanel
    // can not use display width/height because of notification bar
    ViewTreeObserver vto = tableLayout.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {

            // get values of portrait mode

            Display display = getWindowManager().getDefaultDisplay();

            if (display.getRotation() == Surface.ROTATION_0) {
                width = tableLayout.getWidth();
                height = tableLayout.getHeight();
            } else {
                height = tableLayout.getWidth();
                width = tableLayout.getHeight();
            }

            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ccp000);
            bmp = Bitmap.createScaledBitmap(bmp, width, height, true);
            Drawable d = new BitmapDrawable(getResources(), bmp);
            bmp = null; // prevent outofmemor
            tableLayout.setBackgroundDrawable(d);

            touchlistener = new TouchListener(linlGrid, width, height, handler);
            tableLayout.setOnTouchListener(touchlistener);
            // remove listener again otherwise it gets called twice
            tableLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
    });
}

From source file:com.rareventure.gps2.reviewer.SettingsActivity.java

@Override
public void doOnResume() {
    super.doOnResume();
    enablePassword.setChecked(!GpsTrailerCrypt.prefs.isNoPassword);
    isCollectData.setChecked(GTG.prefs.isCollectData);
    percTimeGpsOn.setValue(GpsTrailerGpsStrategy.prefs.batteryGpsOnTimePercentage * 100);
    minBatteryLife.setValue(GTG.prefs.minBatteryPerc * 100);
    enableToolTips.setChecked(OsmMapGpsTrailerReviewerMapActivity.prefs.enableToolTips);
    mapFontSize.setValue(OsmMapGpsTrailerReviewerMapActivity.prefs.panelScale);
    passwordTimeout.setValue(getPasswordTimeoutFromMS(GTG.prefs.passwordTimeoutMS));

    passwordTimeout.setEnabled(enablePassword.isChecked());

    //co: we no longer allow access to application after expiry (so we can justify not
    // serving tiles without a valid license)
    //        if(GTG.isTrialPeriodExpired())
    //        {/*from  www.ja v a2s  .c  o m*/
    //           isCollectData.setEnabled(false);
    //           isCollectData.setChecked(false);
    //        }

    if (GTG.lastSuccessfulAction == GTGAction.TOOL_TIP_CLICKED) {
        GTG.lastSuccessfulAction = null;

        //scroll done to tool tip option
        ViewTreeObserver vto = getListView().getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                PreferenceScreen screen = getPreferenceScreen();
                int i;
                for (i = 0; i < screen.getPreferenceCount(); i++) {
                    Preference p = screen.getPreference(i);

                    if (p == enableToolTips)
                        break;
                }

                getListView().setSelection(i);

                getListView().getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });

    }

}

From source file:org.onebusaway.android.ui.TripPlanActivity.java

@Override
protected void onResume() {
    super.onResume();

    Bundle bundle = mBuilder.getBundle();
    boolean newItineraries = false;

    // see if there is data from intent
    Intent intent = getIntent();/*from  w w w  .  j  a  va2  s .co m*/

    if (intent != null && intent.getExtras() != null) {

        OTPConstants.Source source = (OTPConstants.Source) intent
                .getSerializableExtra(OTPConstants.INTENT_SOURCE);
        if (source != null) {

            // Copy planning params - necessary if this intent came from a notification.
            if (source == OTPConstants.Source.NOTIFICATION) {
                new TripRequestBuilder(intent.getExtras()).copyIntoBundle(bundle);
            }

            ArrayList<Itinerary> itineraries = (ArrayList<Itinerary>) intent.getExtras()
                    .getSerializable(OTPConstants.ITINERARIES);

            if (itineraries != null) {
                bundle.putSerializable(OTPConstants.ITINERARIES, itineraries);
                newItineraries = true;
            }

            if (intent.getIntExtra(PLAN_ERROR_CODE, -1) != -1) {
                bundle.putSerializable(SHOW_ERROR_DIALOG, true);
                bundle.putInt(PLAN_ERROR_CODE, intent.getIntExtra(PLAN_ERROR_CODE, 0));
                bundle.putString(PLAN_ERROR_URL, intent.getStringExtra(PLAN_ERROR_URL));
            }

            setIntent(null);
            bundle.putBoolean(REQUEST_LOADING, false);
            mRequestLoading = false;

        }
    }

    if (mRequestLoading || bundle.getBoolean(REQUEST_LOADING)) {
        showProgressDialog();
    }

    // Check which fragment to create
    boolean haveTripPlan = bundle.getSerializable(OTPConstants.ITINERARIES) != null;

    TripPlanFragment fragment = (TripPlanFragment) getSupportFragmentManager()
            .findFragmentById(R.id.trip_plan_fragment_container);
    if (fragment == null) {
        fragment = new TripPlanFragment();
        fragment.setArguments(bundle);
        fragment.setListener(this);
        getSupportFragmentManager().beginTransaction().add(R.id.trip_plan_fragment_container, fragment)
                .commit();
    }

    mPanel = (SlidingUpPanelLayout) findViewById(R.id.trip_plan_sliding_layout);

    mPanel.setEnabled(haveTripPlan);

    if (haveTripPlan) {
        initResultsFragment();
        if (bundle.getBoolean(PANEL_STATE_EXPANDED) || newItineraries) {
            mPanel.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
        }
    }

    // show error dialog if necessary
    if (bundle.getBoolean(SHOW_ERROR_DIALOG)) {
        int planErrorCode = intent.getIntExtra(PLAN_ERROR_CODE, 0);
        String planErrorUrl = intent.getStringExtra(PLAN_ERROR_URL);
        showFeedbackDialog(planErrorCode, planErrorUrl);
    }

    if (fragment != null && intent != null) {
        fragment.setPlanErrorUrl(intent.getStringExtra(PLAN_ERROR_URL));
        fragment.setPlanRequestUrl(intent.getStringExtra(PLAN_REQUEST_URL));
    }

    // Set the height of the panel after drawing occurs.
    final ViewGroup layout = (ViewGroup) findViewById(R.id.trip_plan_fragment_container);
    ViewTreeObserver vto = layout.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            int viewHeight = mPanel.getHeight();
            int height = layout.getMeasuredHeight();
            mPanel.setPanelHeight(viewHeight - height);
        }
    });
}

From source file:ca.zadrox.dota2esportticker.ui.TeamDetailActivity.java

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

    getLoaderManager().initLoader(GGLOADER_ID, null, ggTeamLoaderCallbacks);

    final Toolbar toolbar = getActionBarToolbar();
    toolbar.setNavigationIcon(R.drawable.ic_up);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override/*from   ww w  . j a v a 2  s .com*/
        public void onClick(View v) {
            onBackPressed();
        }
    });

    mHandler.post(new Runnable() {
        @Override
        public void run() {
            toolbar.setTitle("");
        }
    });

    mMaxHeaderElevation = getResources().getDimensionPixelSize(R.dimen.session_detail_max_header_elevation);

    mScrollView = (ObservableScrollView) findViewById(R.id.scroll_view);
    mScrollView.addCallbacks(this);
    ViewTreeObserver vto = mScrollView.getViewTreeObserver();
    if (vto.isAlive()) {
        vto.addOnGlobalLayoutListener(mGlobalLayoutListener);
    }

    mScrollViewChild = findViewById(R.id.scroll_view_child);
    mHeaderBox = (FrameLayout) findViewById(R.id.header_bar);

    mHeaderTeamName = (TextView) mHeaderBox.findViewById(R.id.team_name);
    mHeaderTeamLogo = (BezelImageView) mHeaderBox.findViewById(R.id.team_logo);
    mHeaderTeamLogo.setVisibility(View.INVISIBLE);

    mHeaderTeamName.getLayoutParams().height = UIUtils.calculateActionBarSize(this);
    mHeaderTeamName.setAlpha(0f);

    mDetailsContainer = (LinearLayout) mScrollViewChild.findViewById(R.id.card_container);

    recomputeScrollingConstants();

}

From source file:gov.sfmta.sfpark.AnnotationsOverlay.java

@Override
protected boolean onTap(final int index) {
    Log.v(TAG, "onTap");

    if (isPinch) {
        return false;
    }/*from w  w  w  .  jav a  2s.  c  o  m*/

    aa = MainScreenActivity.annotations.get(index);

    if (aa == null) {
        return false;
    }

    try {
        aa.subtitle = aa.availabilityDescriptionShowingPrice(MainScreenActivity.showPrice);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    GeoPoint geoPoint = aa.mid;

    LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    popupView = vi.inflate(R.layout.dialog, null);

    TextView title = (TextView) popupView.findViewById(R.id.detailTitle);
    TextView subtitle = (TextView) popupView.findViewById(R.id.detailSubtitle);
    title.setTextColor(0xFFffffff);
    subtitle.setTextColor(0xFFcccccc);

    // set bubble title
    title.setText(aa.title != null ? aa.title : mContext.getString(R.string.unknown));

    // Bubble Flurry!
    Map<String, String> details = new HashMap<String, String>();
    details.put("Details for", aa.title);
    FlurryAgent.logEvent("Show_Details", details);

    // set bubble subtitle
    if (aa.subtitle == null) {
        subtitle.setText(R.string.full);
        aa.subtitle = mContext.getString(R.string.full);
    } else {
        if (aa.onStreet) {
            subtitle.setText(aa.subtitle);
        } else {
            if (aa.subtitle.startsWith("Estimated 0 of") || aa.subtitle.startsWith("Estimated -")
                    || aa.subtitle.startsWith("-")) {
                subtitle.setText(R.string.full);
                aa.subtitle = mContext.getString(R.string.full);
            } else {
                subtitle.setText(aa.subtitle);
            }
        }
    }

    LayoutParams mapDialogParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, geoPoint, 0, -20, LayoutParams.CENTER);
    MainScreenActivity.mapView.addView(popupView, mapDialogParams);

    popupView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.v(TAG, "Details tapped");

            // Bubble Flurry!
            Map<String, String> moreDetails = new HashMap<String, String>();
            moreDetails.put("Details for", aa.title);
            FlurryAgent.logEvent("Show_More_Details", moreDetails);

            DetailViewActivity.present(mContext, aa);
            return;
        }
    });

    //PreDraw creates infinite loop situations
    ViewTreeObserver vto = popupView.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            Log.v(TAG, "onGlobalLayout");

            if ((aa == null) || (MainScreenActivity.mapView == null) || (MainScreenActivity.mc == null)
                    || (popupView == null)) {
                return;
            }

            // compromise until figure out horiz Point
            // offset(dx, 0) projection toPixels fromPixels
            // dip - pixels - lon getMeasuredWidth etc
            if ((popupView.getLeft() < MainScreenActivity.mapView.getLeft())
                    || (popupView.getRight() > MainScreenActivity.mapView.getRight())) {
                // assumes aa is set!
                MainScreenActivity.mc.animateTo(aa.mid);
            }

            // Separated for clarity - something missing re
            // -20 at top and view height at bottom...

            if ((popupView.getTop() < MainScreenActivity.mapView.getTop())
                    || (popupView.getBottom() > MainScreenActivity.mapView.getBottom())) {
                // assumes aa is set!
                MainScreenActivity.mc.animateTo(aa.mid);
            }

            // make sure only called one time!
            popupView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
    });

    return true;
}

From source file:com.partynetwork.iparty.app.widget.crouton.Manager.java

/**
 * Adds a {@link Crouton} to the {@link ViewParent} of it's {@link Activity}
 * ./*from   w  w  w .  ja v a  2 s . c  o m*/
 * 
 * @param crouton
 *            The {@link Crouton} that should be added.
 */
private void addCroutonToView(final Crouton crouton) {
    // don't add if it is already showing
    if (crouton.isShowing()) {
        return;
    }

    final View croutonView = crouton.getView();
    if (null == croutonView.getParent()) {
        ViewGroup.LayoutParams params = croutonView.getLayoutParams();
        if (null == params) {
            params = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        // display Crouton in ViewGroup is it has been supplied
        if (null != crouton.getViewGroup()) {
            // TODO implement add to last position feature (need to align
            // with how this will be requested for activity)
            if (crouton.getViewGroup() instanceof FrameLayout) {
                crouton.getViewGroup().addView(croutonView, params);
            } else {
                crouton.getViewGroup().addView(croutonView, 0, params);
            }
        } else {
            Activity activity = crouton.getActivity();
            if (null == activity || activity.isFinishing()) {
                return;
            }

            activity.addContentView(croutonView, params);
        }
    }

    croutonView.requestLayout(); // This is needed so the animation can use
    // the measured with/height
    ViewTreeObserver observer = croutonView.getViewTreeObserver();
    if (null != observer) {
        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            @TargetApi(16)
            public void onGlobalLayout() {

                croutonView.getViewTreeObserver().removeGlobalOnLayoutListener(this);

                croutonView.startAnimation(crouton.getInAnimation());
                announceForAccessibilityCompat(crouton.getActivity(), crouton.getText());
                if (Configuration.DURATION_INFINITE != crouton.getConfiguration().durationInMilliseconds) {
                    sendMessageDelayed(crouton, Messages.REMOVE_CROUTON,
                            crouton.getConfiguration().durationInMilliseconds
                                    + crouton.getInAnimation().getDuration());
                }
            }
        });
    }
}

From source file:org.openbmap.activities.CellDetailsMap.java

/**
 * Initializes map components//w ww  .java2s .c  om
 */
@SuppressLint("NewApi")
private void initMap() {
    this.mTileCache = createTileCache();

    if (MapUtils.isMapSelected(this.getActivity())) {
        final Layer offlineLayer = MapUtils.createTileRendererLayer(this.mTileCache,
                this.mMapView.getModel().mapViewPosition, getMapFile(), null, getRenderTheme());
        if (offlineLayer != null)
            this.mMapView.getLayerManager().getLayers().add(offlineLayer);
    } else {
        //this.mMapView.getModel().displayModel.setBackgroundColor(0xffffffff);
        Toast.makeText(this.getActivity(), R.string.info_using_online_map, Toast.LENGTH_LONG).show();

        final OnlineTileSource onlineTileSource = new OnlineTileSource(
                new String[] { "otile1.mqcdn.com", "otile2.mqcdn.com", "otile3.mqcdn.com", "otile4.mqcdn.com" },
                80);
        onlineTileSource.setName("MapQuest").setAlpha(false).setBaseUrl("/tiles/1.0.0/map/").setExtension("png")
                .setParallelRequestsLimit(8).setProtocol("http").setTileSize(256).setZoomLevelMax((byte) 18)
                .setZoomLevelMin((byte) 0);

        mapDownloadLayer = new TileDownloadLayer(mTileCache, mMapView.getModel().mapViewPosition,
                onlineTileSource, AndroidGraphicFactory.INSTANCE);
        mMapView.getLayerManager().getLayers().add(mapDownloadLayer);
        mapDownloadLayer.onResume();
    }

    // register for layout finalization - we need this to get width and height
    final ViewTreeObserver vto = mMapView.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @SuppressLint("NewApi")
        @Override
        public void onGlobalLayout() {

            mLayoutInflated = true;
            proceedAfterHeatmapCompleted();

            final ViewTreeObserver obs = mMapView.getViewTreeObserver();

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                obs.removeOnGlobalLayoutListener(this);
            } else {
                obs.removeGlobalOnLayoutListener(this);
            }
        }
    });

    // Register for zoom changes
    this.mMapObserver = new Observer() {
        @Override
        public void onChange() {

            final byte newZoom = mMapView.getModel().mapViewPosition.getZoomLevel();
            if (newZoom != mCurrentZoom) {
                // update overlays on zoom level changed
                Log.i(TAG, "New zoom level " + newZoom + ", reloading map objects");
                Log.i(TAG, "Update" + mUpdatePending);
                // cancel pending heat-maps
                //if (builder != null) {
                //   builder.cancel(true);
                //}

                // if another update is pending, wait for complete
                if (!mUpdatePending) {
                    clearLayer();
                    proceedAfterHeatmapCompleted();
                }
                mCurrentZoom = newZoom;
            }
        }
    };
    this.mMapView.getModel().mapViewPosition.addObserver(mMapObserver);

    this.mMapView.setClickable(true);
    this.mMapView.getMapScaleBar().setVisible(true);

    this.mMapView.getModel().mapViewPosition.setZoomLevel((byte) 16);
}

From source file:com.arta.lib.widget.crouton.Manager.java

/**
 * Adds a {@link Crouton} to the {@link ViewParent} of it's {@link Activity}.
 *
 * @param crouton/*w w w.jav  a 2s .c om*/
 *     The {@link Crouton} that should be added.
 */
private void addCroutonToView(final Crouton crouton) {
    // don't add if it is already showing
    if (crouton.isShowing()) {
        return;
    }

    final View croutonView = crouton.getView();
    if (null == croutonView.getParent()) {
        ViewGroup.LayoutParams params = croutonView.getLayoutParams();
        if (null == params) {
            params = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        // display Crouton in ViewGroup is it has been supplied
        if (null != crouton.getViewGroup()) {
            // TODO implement add to last position feature (need to align with how this will be requested for activity)
            if (crouton.getViewGroup() instanceof FrameLayout) {
                crouton.getViewGroup().addView(croutonView, params);
            } else {
                crouton.getViewGroup().addView(croutonView, 0, params);
            }
        } else {
            Activity activity = crouton.getActivity();
            if (null == activity || activity.isFinishing()) {
                return;
            }
            handleTranslucentActionBar((ViewGroup.MarginLayoutParams) params, activity);

            activity.addContentView(croutonView, params);
        }
    }

    croutonView.requestLayout(); // This is needed so the animation can use the measured with/height
    ViewTreeObserver observer = croutonView.getViewTreeObserver();
    if (null != observer) {
        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            @TargetApi(16)
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                    croutonView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    croutonView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }

                croutonView.startAnimation(crouton.getInAnimation());
                announceForAccessibilityCompat(crouton.getActivity(), crouton.getText());
                if (Configuration.DURATION_INFINITE != crouton.getConfiguration().durationInMilliseconds) {
                    sendMessageDelayed(crouton, Messages.REMOVE_CROUTON,
                            crouton.getConfiguration().durationInMilliseconds
                                    + crouton.getInAnimation().getDuration());
                }
            }
        });
    }
}

From source file:com.example.androidannotationtesttwo.widget.crouton.Manager.java

/**
 * Adds a {@link Crouton} to the {@link ViewParent} of it's {@link Activity}
 * .//from   ww  w .j  av  a2s .c om
 * 
 * @param crouton The {@link Crouton} that should be added.
 */
private void addCroutonToView(final Crouton crouton) {
    // don't add if it is already showing
    if (crouton.isShowing()) {
        return;
    }

    final View croutonView = crouton.getView();
    if (null == croutonView.getParent()) {
        ViewGroup.LayoutParams params = croutonView.getLayoutParams();
        if (null == params) {
            params = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        // display Crouton in ViewGroup is it has been supplied
        if (null != crouton.getViewGroup()) {
            // TODO implement add to last position feature (need to align
            // with how this will be requested for activity)
            if (crouton.getViewGroup() instanceof FrameLayout) {
                crouton.getViewGroup().addView(croutonView, params);
            } else {
                crouton.getViewGroup().addView(croutonView, 0, params);
            }
        } else {
            Activity activity = crouton.getActivity();
            if (null == activity || activity.isFinishing()) {
                return;
            }
            handleTranslucentActionBar((ViewGroup.MarginLayoutParams) params, activity);

            activity.addContentView(croutonView, params);
        }
    }

    croutonView.requestLayout(); // This is needed so the animation can use
                                 // the measured with/height
    ViewTreeObserver observer = croutonView.getViewTreeObserver();
    if (null != observer) {
        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            @TargetApi(16)
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                    croutonView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    croutonView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }

                croutonView.startAnimation(crouton.getInAnimation());
                announceForAccessibilityCompat(crouton.getActivity(), crouton.getText());
                if (Configuration.DURATION_INFINITE != crouton.getConfiguration().durationInMilliseconds) {
                    sendMessageDelayed(crouton, Messages.REMOVE_CROUTON,
                            crouton.getConfiguration().durationInMilliseconds
                                    + crouton.getInAnimation().getDuration());
                }
            }
        });
    }
}