List of usage examples for android.view View getViewTreeObserver
public ViewTreeObserver getViewTreeObserver()
From source file:com.androidinspain.deskclock.timer.TimerFragment.java
/** * @param toView one of {@link #mTimersView} or {@link #mCreateTimerView} * @param timerToRemove the timer to be removed during the animation; {@code null} if no timer * should be removed//from www . j a v a 2 s . c om * @param animateDown {@code true} if the views should animate upwards, otherwise downwards */ private void animateToView(final View toView, final Timer timerToRemove, final boolean animateDown) { if (mCurrentView == toView) { return; } final boolean toTimers = toView == mTimersView; if (toTimers) { mTimersView.setVisibility(VISIBLE); } else { mCreateTimerView.setVisibility(VISIBLE); } // Avoid double-taps by enabling/disabling the set of buttons active on the new view. updateFab(BUTTONS_DISABLE); final long animationDuration = UiDataModel.getUiDataModel().getLongAnimationDuration(); final ViewTreeObserver viewTreeObserver = toView.getViewTreeObserver(); viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { if (viewTreeObserver.isAlive()) { viewTreeObserver.removeOnPreDrawListener(this); } final View view = mTimersView.findViewById(com.androidinspain.deskclock.R.id.timer_time); final float distanceY = view != null ? view.getHeight() + view.getY() : 0; final float translationDistance = animateDown ? distanceY : -distanceY; toView.setTranslationY(-translationDistance); mCurrentView.setTranslationY(0f); toView.setAlpha(0f); mCurrentView.setAlpha(1f); final Animator translateCurrent = ObjectAnimator.ofFloat(mCurrentView, TRANSLATION_Y, translationDistance); final Animator translateNew = ObjectAnimator.ofFloat(toView, TRANSLATION_Y, 0f); final AnimatorSet translationAnimatorSet = new AnimatorSet(); translationAnimatorSet.playTogether(translateCurrent, translateNew); translationAnimatorSet.setDuration(animationDuration); translationAnimatorSet.setInterpolator(AnimatorUtils.INTERPOLATOR_FAST_OUT_SLOW_IN); final Animator fadeOutAnimator = ObjectAnimator.ofFloat(mCurrentView, ALPHA, 0f); fadeOutAnimator.setDuration(animationDuration / 2); fadeOutAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { super.onAnimationStart(animation); // The fade-out animation and fab-shrinking animation should run together. updateFab(FAB_AND_BUTTONS_SHRINK); } @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); if (toTimers) { showTimersView(FAB_AND_BUTTONS_EXPAND); // Reset the state of the create view. mCreateTimerView.reset(); } else { showCreateTimerView(FAB_AND_BUTTONS_EXPAND); } if (timerToRemove != null) { DataModel.getDataModel().removeTimer(timerToRemove); Events.sendTimerEvent(com.androidinspain.deskclock.R.string.action_delete, com.androidinspain.deskclock.R.string.label_deskclock); } // Update the fab and button states now that the correct view is visible and // before the animation to expand the fab and buttons starts. updateFab(FAB_AND_BUTTONS_IMMEDIATE); } }); final Animator fadeInAnimator = ObjectAnimator.ofFloat(toView, ALPHA, 1f); fadeInAnimator.setDuration(animationDuration / 2); fadeInAnimator.setStartDelay(animationDuration / 2); final AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playTogether(fadeOutAnimator, fadeInAnimator, translationAnimatorSet); animatorSet.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); mTimersView.setTranslationY(0f); mCreateTimerView.setTranslationY(0f); mTimersView.setAlpha(1f); mCreateTimerView.setAlpha(1f); } }); animatorSet.start(); return true; } }); }
From source file:com.tobrun.vision.qr.QRScanFragment.java
private void onCreateDetector(@NonNull final View view) { final Context context = view.getContext().getApplicationContext(); final BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(context).build(); barcodeDetector.setProcessor(new MultiProcessor.Builder<>(new MultiProcessor.Factory<Barcode>() { @Override// w ww . ja v a 2s . com public Tracker<Barcode> create(final Barcode barcode) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { mCallback.onScanComplete(barcode.displayValue); mPreview.stop(); } }); return new Tracker<>(); } }).build()); if (!barcodeDetector.isOperational()) { IntentFilter lowStorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW); if (context.registerReceiver(null, lowStorageFilter) != null) { // Low storage mCallback.onCameraError(R.string.camera_error_low_storage); } else { // Native libs unavailable mCallback.onCameraError(R.string.camera_error_dependencies); } return; } final ViewTreeObserver observer = view.getViewTreeObserver(); observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { view.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { view.getViewTreeObserver().removeOnGlobalLayoutListener(this); } CameraSource.Builder builder = new CameraSource.Builder(context, barcodeDetector) .setFacing(CameraSource.CAMERA_FACING_BACK) .setRequestedPreviewSize(view.getMeasuredWidth(), view.getMeasuredHeight()) .setRequestedFps(30.0f); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { builder = builder.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); } mCameraSource = builder.build(); startCameraSource(); } }); }
From source file:com.appolica.interactiveinfowindow.InfoWindowManager.java
private void animateWindowOpen(@NonNull final InfoWindow infoWindow, @NonNull final View container) { final SimpleAnimationListener animationListener = new SimpleAnimationListener() { @Override/*from w ww.j a v a 2s . c om*/ public void onAnimationStart(Animation animation) { container.setVisibility(View.VISIBLE); propagateShowEvent(infoWindow, InfoWindow.State.SHOWING); } @Override public void onAnimationEnd(Animation animation) { propagateShowEvent(infoWindow, InfoWindow.State.SHOWN); setCurrentWindow(infoWindow); } }; if (showAnimation == null) { container.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { final int containerWidth = container.getWidth(); final int containerHeight = container.getHeight(); final float pivotX = container.getX() + containerWidth / 2; final float pivotY = container.getY() + containerHeight; final ScaleAnimation scaleAnimation = new ScaleAnimation(0f, 1f, 0f, 1f, pivotX, pivotY); scaleAnimation.setDuration(DURATION_WINDOW_ANIMATION); scaleAnimation.setInterpolator(new DecelerateInterpolator()); scaleAnimation.setAnimationListener(animationListener); container.startAnimation(scaleAnimation); container.getViewTreeObserver().removeOnPreDrawListener(this); return true; } }); } else { showAnimation.setAnimationListener(animationListener); container.startAnimation(showAnimation); } }
From source file:com.iiordanov.bVNC.RemoteCanvasActivity.java
void continueConnecting() { // TODO: Implement left-icon //requestWindowFeature(Window.FEATURE_LEFT_ICON); //setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.icon); setContentView(R.layout.canvas);// w ww.j a va 2 s. com canvas = (RemoteCanvas) findViewById(R.id.vnc_canvas); zoomer = (ZoomControls) findViewById(R.id.zoomer); // Initialize and define actions for on-screen keys. initializeOnScreenKeys(); canvas.initializeCanvas(connection, database, new Runnable() { public void run() { try { setModes(); } catch (NullPointerException e) { } } }); canvas.setOnKeyListener(this); canvas.setFocusableInTouchMode(true); canvas.setDrawingCacheEnabled(false); // This code detects when the soft keyboard is up and sets an appropriate visibleHeight in vncCanvas. // When the keyboard is gone, it resets visibleHeight and pans zero distance to prevent us from being // below the desktop image (if we scrolled all the way down when the keyboard was up). // TODO: Move this into a separate thread, and post the visibility changes to the handler. // to avoid occupying the UI thread with this. final View rootView = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0); rootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Rect r = new Rect(); rootView.getWindowVisibleDisplayFrame(r); // To avoid setting the visible height to a wrong value after an screen unlock event // (when r.bottom holds the width of the screen rather than the height due to a rotation) // we make sure r.top is zero (i.e. there is no notification bar and we are in full-screen mode) // It's a bit of a hack. if (r.top == 0) { if (canvas.bitmapData != null) { canvas.setVisibleHeight(r.bottom); canvas.pan(0, 0); } } // Enable/show the zoomer if the keyboard is gone, and disable/hide otherwise. // We detect the keyboard if more than 19% of the screen is covered. int offset = 0; int rootViewHeight = rootView.getHeight(); if (r.bottom > rootViewHeight * 0.81) { offset = rootViewHeight - r.bottom; // Soft Kbd gone, shift the meta keys and arrows down. if (layoutKeys != null) { layoutKeys.offsetTopAndBottom(offset); keyStow.offsetTopAndBottom(offset); if (prevBottomOffset != offset) { setExtraKeysVisibility(View.GONE, false); canvas.invalidate(); zoomer.enable(); } } } else { offset = r.bottom - rootViewHeight; // Soft Kbd up, shift the meta keys and arrows up. if (layoutKeys != null) { layoutKeys.offsetTopAndBottom(offset); keyStow.offsetTopAndBottom(offset); if (prevBottomOffset != offset) { setExtraKeysVisibility(View.VISIBLE, true); canvas.invalidate(); zoomer.hide(); zoomer.disable(); } } } setKeyStowDrawableAndVisibility(); prevBottomOffset = offset; } }); zoomer.hide(); zoomer.setOnZoomKeyboardClickListener(new View.OnClickListener() { @Override public void onClick(View v) { InputMethodManager inputMgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMgr.toggleSoftInput(0, 0); } }); zoomer.setOnShowMenuClickListener(new View.OnClickListener() { @Override public void onClick(View v) { RemoteCanvasActivity.this.openOptionsMenu(); } }); panner = new Panner(this, canvas.handler); inputHandler = getInputHandlerById(R.id.itemInputTouchPanZoomMouse); }
From source file:org.cm.podd.report.activity.ReportActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this); broadcastManager.registerReceiver(mAlertReceiver, new IntentFilter(FollowAlertService.TAG)); broadcastManager.registerReceiver(new BroadcastReceiver() { @Override//from w w w .ja v a 2 s.c o m public void onReceive(Context context, Intent intent) { long administrationAreaId = intent.getLongExtra("administrationAreaId", -99); setRegionId(administrationAreaId); } }, new IntentFilter(SyncAdministrationAreaService.TAG)); sharedPrefUtil = new SharedPrefUtil(this); setContentView(R.layout.activity_report); Toolbar myToolbar = findViewById(R.id.report_toolbar); setSupportActionBar(myToolbar); long areaId = sharedPrefUtil.getDefaultAdministrationAreaId(); if (areaId != -99) { setRegionId(areaId); } formView = findViewById(R.id.form); locationView = findViewById(R.id.location); textProgressLocationView = findViewById(R.id.progress_location_text); textProgressLocationView.setTypeface(StyleUtil.getDefaultTypeface(getAssets(), Typeface.NORMAL)); countdownTextView = findViewById(R.id.countdownTextView); countdownTextView.setTypeface(StyleUtil.getDefaultTypeface(getAssets(), Typeface.NORMAL)); refreshLocationButton = findViewById(R.id.refresh_location_button); refreshLocationButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { requestGPSLocation(); startLocationSearchTimeoutCountdown(); } }); progressBar = findViewById(R.id.progressBar); prevBtn = findViewById(R.id.prevBtn); nextBtn = findViewById(R.id.nextBtn); nextBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { nextScreen(); } }); nextBtn.setTypeface(StyleUtil.getDefaultTypeface(getAssets(), Typeface.NORMAL)); prevBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onBackPressed(); } }); prevBtn.setTypeface(StyleUtil.getDefaultTypeface(getAssets(), Typeface.NORMAL)); disableMaskView = findViewById(R.id.disableMask); reportDataSource = new ReportDataSource(this); reportTypeDataSource = new ReportTypeDataSource(this); reportQueueDataSource = new ReportQueueDataSource(this); recordSpecDataSource = RecordSpecDataSource.Companion.getInstance(this); followAlertDataSource = new FollowAlertDataSource(this); if (savedInstanceState != null) { currentFragment = savedInstanceState.getString("currentFragment"); reportId = savedInstanceState.getLong("reportId"); reportType = savedInstanceState.getLong("reportType"); follow = savedInstanceState.getBoolean("follow"); testReport = savedInstanceState.getBoolean("testReport"); formIterator = (FormIterator) savedInstanceState.getSerializable("formIterator"); if (formIterator != null) { trigger = formIterator.getForm().getTrigger(); } reportSubmit = savedInstanceState.getInt("reportSubmit"); followActionName = savedInstanceState.getString("followActionName"); Log.d(TAG, "onCreate from savedInstance, testFlag = " + testReport); currentLatitude = savedInstanceState.getDouble("currentLatitude"); currentLongitude = savedInstanceState.getDouble("currentLongitude"); recordSpec = (RecordSpec) savedInstanceState.get("recordSpec"); parentReportGuid = savedInstanceState.getString("parentReportGuid"); } else { Intent intent = getIntent(); String action = intent.getAction(); int startPageId = -1; switch (action) { case ACTION_NEW_REPORT: reportType = intent.getLongExtra("reportType", 0); testReport = intent.getBooleanExtra("test", false); reportId = reportDataSource.createDraftReport(reportType, testReport); follow = false; break; case FollowAlertService.ORG_CM_PODD_REPORT_FOLLOW: reportType = intent.getLongExtra("reportType", 0); testReport = false; reportId = intent.getLongExtra("reportId", -99); follow = intent.getBooleanExtra("follow", false); break; case ACTION_FOR_EDIT_OR_VIEW: reportType = intent.getLongExtra("reportType", 0); testReport = intent.getBooleanExtra("test", false); reportId = intent.getLongExtra("reportId", -99); break; case ACTION_CREATE_FOLLOW_REPORT: reportType = intent.getLongExtra("reportType", 0); parentReportId = intent.getLongExtra("reportId", -99); reportId = reportDataSource.createFollowReport(parentReportId); follow = true; followActionName = "follow"; break; case ACTION_CREATE_FOLLOW_REPORT_WITH_ACTION: reportType = intent.getLongExtra("reportType", 0); parentReportId = intent.getLongExtra("reportId", -99); reportId = reportDataSource.createFollowReport(parentReportId); follow = true; followActionName = intent.getStringExtra("followActionName"); startPageId = intent.getIntExtra("startPageId", -1); break; case ACTION_CREATE_FOLLOW_REPORT_FROM_RECORD: reportType = intent.getLongExtra("reportType", 0); parentReportGuid = intent.getStringExtra("parentReportGuid"); String preloadFormData = intent.getStringExtra("preloadFormData"); reportId = reportDataSource.createFollowReport(reportType, parentReportGuid, preloadFormData); follow = true; break; } Form form = reportTypeDataSource.getForm(reportType); trigger = form.getTrigger(); if (trigger != null) { Log.d(TAG, String.format( "This report type contain a trigger with pattern:%s, pageId:%d, notificationText:%s", trigger.getPattern(), trigger.getPageId(), trigger.getNotificationText())); } if (intent.getAction() != null && intent.getAction().equals(FollowAlertService.ORG_CM_PODD_REPORT_FOLLOW)) { form.setStartWithTrigger(true); } if (startPageId != -1) { form.setStartPageId(startPageId); } formIterator = new FormIterator(form); Report report = loadFormData(form); recordSpec = recordSpecDataSource.getByReportTypeId(report.getType()); nextScreen(); } if (recordSpec != null) { final FirebaseContext firebaseContext = FirebaseContext.Companion .getInstance(PreferenceContext.Companion.getInstance(getApplicationContext())); firebaseContext.auth(this, new Function1<Boolean, Unit>() { @Override public Unit invoke(Boolean success) { if (success) { recordDataSource = firebaseContext.recordDataSource(recordSpec, parentReportGuid); } return null; } }); } // open location service only when // 1. Create a New report // 2. Edit a draft report which don't have any location attach. if ((reportSubmit == 0) && (currentLatitude == 0.00)) { buildGoogleApiClient(); if (formIterator.getForm().isForceLocation()) { switchToProgressLocationMode(); } } /* check softkeyboard visibility */ final View rootView = getWindow().getDecorView().findViewById(android.R.id.content); rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // different devices' screens have normal height diff differently // eg, roughly 5.5" xxhdpi has 220px, 4.5" xhdpi has 110px, 4", 3.5" hdpi has 75px int heightDiff = rootView.getRootView().getHeight() - rootView.getHeight(); int limitHeightPx = (int) (getResources().getDisplayMetrics().density * 100); Log.d(TAG, String.format("diff height=%d, limit height=%d", heightDiff, limitHeightPx)); } }); Tracker tracker = ((PoddApplication) getApplication()).getTracker(PoddApplication.TrackerName.APP_TRACKER); tracker.setScreenName("Report-" + reportType); tracker.send(new HitBuilders.AppViewBuilder().build()); startTime = System.currentTimeMillis(); }
From source file:com.google.android.apps.muzei.settings.ChooseSourceFragment.java
@Override public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) { // Ensure we have the latest insets view.requestFitSystemWindows();/*from w ww .j a v a 2 s .c o m*/ mScrollbar = view.findViewById(R.id.source_scrollbar); mSourceScrollerView = view.findViewById(R.id.source_scroller); mSourceScrollerView.setCallbacks(new ObservableHorizontalScrollView.Callbacks() { @Override public void onScrollChanged(int scrollX) { showScrollbar(); } @Override public void onDownMotionEvent() { if (mCurrentScroller != null) { mCurrentScroller.cancel(); mCurrentScroller = null; } } }); mSourceContainerView = view.findViewById(R.id.source_container); redrawSources(); view.setVisibility(View.INVISIBLE); view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { int mPass = 0; @Override public void onGlobalLayout() { if (mPass == 0) { // First pass updatePadding(); ++mPass; } else if (mPass == 1 & mSelectedSourceIndex >= 0) { // Second pass mSourceScrollerView.setScrollX(mItemWidth * mSelectedSourceIndex); showScrollbar(); view.setVisibility(View.VISIBLE); ++mPass; } else { // Last pass, remove the listener view.getViewTreeObserver().removeOnGlobalLayoutListener(this); } } }); view.setAlpha(0); view.animate().alpha(1f).setDuration(500); }
From source file:com.example.ray.firstapp.bottombar.BottomBar.java
private static void navBarMagic(Activity activity, final BottomBar bottomBar) { Resources res = activity.getResources(); int softMenuIdentifier = res.getIdentifier("config_showNavigationBar", "bool", "android"); int navBarIdentifier = res.getIdentifier("navigation_bar_height", "dimen", "android"); int navBarHeight = 0; if (navBarIdentifier > 0) { navBarHeight = res.getDimensionPixelSize(navBarIdentifier); }/*from w ww. j av a 2 s . c o m*/ if (!bottomBar.drawBehindNavBar() || navBarHeight == 0 || (!(softMenuIdentifier > 0 && res.getBoolean(softMenuIdentifier)))) { return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && ViewConfiguration.get(activity).hasPermanentMenuKey()) { return; } /** * Copy-paste coding made possible by: * http://stackoverflow.com/a/14871974/940036 */ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { Display d = activity.getWindowManager().getDefaultDisplay(); DisplayMetrics realDisplayMetrics = new DisplayMetrics(); d.getRealMetrics(realDisplayMetrics); int realHeight = realDisplayMetrics.heightPixels; int realWidth = realDisplayMetrics.widthPixels; DisplayMetrics displayMetrics = new DisplayMetrics(); d.getMetrics(displayMetrics); int displayHeight = displayMetrics.heightPixels; int displayWidth = displayMetrics.widthPixels; boolean hasSoftwareKeys = (realWidth - displayWidth) > 0 || (realHeight - displayHeight) > 0; if (!hasSoftwareKeys) { return; } } /** * End of delicious copy-paste code */ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { activity.getWindow().getAttributes().flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION; if (bottomBar.useTopOffset()) { int offset; int statusBarResource = res.getIdentifier("status_bar_height", "dimen", "android"); if (statusBarResource > 0) { offset = res.getDimensionPixelSize(statusBarResource); } else { offset = MiscUtils.dpToPixel(activity, 25); } if (!bottomBar.useOnlyStatusbarOffset()) { TypedValue tv = new TypedValue(); if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { offset += TypedValue.complexToDimensionPixelSize(tv.data, res.getDisplayMetrics()); } else { offset += MiscUtils.dpToPixel(activity, 56); } } bottomBar.getUserContainer().setPadding(0, offset, 0, 0); } final View outerContainer = bottomBar.getOuterContainer(); final int navBarHeightCopy = navBarHeight; bottomBar.getViewTreeObserver() .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @SuppressWarnings("deprecation") @Override public void onGlobalLayout() { bottomBar.shyHeightAlreadyCalculated(); int newHeight = outerContainer.getHeight() + navBarHeightCopy; outerContainer.getLayoutParams().height = newHeight; if (bottomBar.isShy()) { int defaultOffset = bottomBar.useExtraOffset() ? navBarHeightCopy : 0; bottomBar.setTranslationY(defaultOffset); ((CoordinatorLayout.LayoutParams) bottomBar.getLayoutParams()) .setBehavior(new BottomNavigationBehavior(newHeight, defaultOffset)); } ViewTreeObserver obs = outerContainer.getViewTreeObserver(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { obs.removeOnGlobalLayoutListener(this); } else { obs.removeGlobalOnLayoutListener(this); } } }); } }
From source file:com.prashant.custom.widget.crouton.Manager.java
/** * Adds a {@link Crouton} to the {@link ViewParent} of it's {@link Activity}. * * @param crouton//from w w w . j a v a 2s . c o m * 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.LayoutParams(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 croutonView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @SuppressWarnings("deprecation") @Override 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.achep.header2actionbar.HeaderFragmentSupportV4.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final Activity activity = getActivity(); assert activity != null; mFrameLayout = new FrameLayout(activity); mHeader = onCreateHeaderView(inflater, mFrameLayout); mHeaderHeader = mHeader.findViewById(android.R.id.title); mHeaderBackground = mHeader.findViewById(android.R.id.background); assert mHeader.getLayoutParams() != null; mHeader.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); mHeaderHeight = mHeader.getMeasuredHeight(); mFakeHeader = new Space(activity); View content = onCreateContentView(inflater, mFrameLayout); mContentView = content;/*w ww. j a va2 s . c o m*/ Log.i(TAG, "container:" + container.getMeasuredHeight() + ",mHeaderHeight=" + mHeaderHeight); final View topContentView = container; if (content instanceof ListView) { isListViewEmpty = true; final ListView listView = (ListView) content; mFakeHeader.setLayoutParams(new ListView.LayoutParams(0, mHeaderHeight)); listView.addHeaderView(mFakeHeader); listView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView absListView, int scrollState) { if (mOnScrollListener != null) { mOnScrollListener.onScrollStateChanged(absListView, scrollState); } } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (isListViewEmpty) { scrollHeaderTo(0); } else { final View child = absListView.getChildAt(0); assert child != null; scrollHeaderTo(child == mFakeHeader ? child.getTop() : -mHeaderHeight); } } }); } else { topContentView.getViewTreeObserver() .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @SuppressWarnings("deprecation") @Override public void onGlobalLayout() { //Remove it here unless you want to get this callback for EVERY //layout pass, which can get you into infinite loops if you ever //modify the layout from within this method. topContentView.getViewTreeObserver().removeGlobalOnLayoutListener(this); //Now you can get the width and height from content int actionBarHeight = 0; TypedValue tv = new TypedValue(); if (getActivity().getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics()); } Log.i(TAG, "topContentView:" + topContentView.getHeight() + ", actionBarHeight:" + actionBarHeight + ", getStatusBarHeight:" + getStatusBarHeight()); ViewGroup.LayoutParams lp = mContentView.getLayoutParams(); lp.height = topContentView.getHeight() - actionBarHeight - getStatusBarHeight(); mContentView.setLayoutParams(lp); } }); // Merge fake header view and content view. final LinearLayout view = new LinearLayout(activity); view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); view.setOrientation(LinearLayout.VERTICAL); mFakeHeader.setLayoutParams(new LinearLayout.LayoutParams(0, mHeaderHeight)); view.addView(mFakeHeader); view.addView(content); // Put merged content to ScrollView final NotifyingScrollView scrollView = new NotifyingScrollView(activity); scrollView.addView(view); scrollView.setVerticalScrollBarEnabled(false); scrollView.setOverScrollMode(ScrollView.OVER_SCROLL_NEVER); scrollView.setOnScrollChangedListener(new NotifyingScrollView.OnScrollChangedListener() { @Override public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) { Log.i(TAG, "onScrollChanged scroll ot -t :" + (-t)); scrollHeaderTo(-t); } }); mContentWrapper = scrollView; content = scrollView; } mFrameLayout.addView(content); mFrameLayout.addView(mHeader); // Content overlay view always shows at the top of content. if ((mContentOverlay = onCreateContentOverlayView(inflater, mFrameLayout)) != null) { mFrameLayout.addView(mContentOverlay, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); } // Post initial scroll mFrameLayout.post(new Runnable() { @Override public void run() { Log.i(TAG, "post initial scroll to 0"); // SEAN: walk around for scroll position bug if (mContentWrapper != null) { mContentWrapper.scrollTo(0, 0); } scrollHeaderTo(0, true); } }); return mFrameLayout; }
From source file:com.machine.custom.view.crouton.Manager.java
/** * Adds a {@link Crouton} to the {@link ViewParent} of it's {@link Activity}. * * @param crouton/* ww w.j a v a 2 s . c o m*/ * 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.LayoutParams(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 croutonView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @SuppressWarnings("deprecation") @Override 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()); } } }); }