List of usage examples for android.support.v4.content ContextCompat getDrawable
public static final Drawable getDrawable(Context context, int i)
From source file:com.farmerbb.notepad.fragment.NoteViewFragment.java
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override/*from ww w . jav a2 s. c o m*/ public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Set values setRetainInstance(true); setHasOptionsMenu(true); // Get filename of saved note filename = getArguments().getString("filename"); // Change window title String title; try { title = listener.loadNoteTitle(filename); } catch (IOException e) { title = getResources().getString(R.string.view_note); } getActivity().setTitle(title); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Bitmap bitmap = ((BitmapDrawable) ContextCompat.getDrawable(getActivity(), R.drawable.ic_recents_logo)) .getBitmap(); ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription(title, bitmap, ContextCompat.getColor(getActivity(), R.color.primary)); getActivity().setTaskDescription(taskDescription); } // Show the Up button in the action bar. ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Animate elevation change if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-large") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { LinearLayout noteViewEdit = getActivity().findViewById(R.id.noteViewEdit); LinearLayout noteList = getActivity().findViewById(R.id.noteList); noteList.animate().z(0f); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) noteViewEdit.animate() .z(getResources().getDimensionPixelSize(R.dimen.note_view_edit_elevation_land)); else noteViewEdit.animate().z(getResources().getDimensionPixelSize(R.dimen.note_view_edit_elevation)); } // Set up content view TextView noteContents = getActivity().findViewById(R.id.textView); markdownView = getActivity().findViewById(R.id.markdownView); // Apply theme SharedPreferences pref = getActivity().getSharedPreferences(getActivity().getPackageName() + "_preferences", Context.MODE_PRIVATE); ScrollView scrollView = getActivity().findViewById(R.id.scrollView); String theme = pref.getString("theme", "light-sans"); int textSize = -1; int textColor = -1; String fontFamily = null; if (theme.contains("light")) { if (noteContents != null) { noteContents.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_color_primary)); noteContents.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background)); } if (markdownView != null) { markdownView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background)); textColor = ContextCompat.getColor(getActivity(), R.color.text_color_primary); } scrollView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background)); } if (theme.contains("dark")) { if (noteContents != null) { noteContents.setTextColor(ContextCompat.getColor(getActivity(), R.color.text_color_primary_dark)); noteContents .setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark)); } if (markdownView != null) { markdownView .setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark)); textColor = ContextCompat.getColor(getActivity(), R.color.text_color_primary_dark); } scrollView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.window_background_dark)); } if (theme.contains("sans")) { if (noteContents != null) noteContents.setTypeface(Typeface.SANS_SERIF); if (markdownView != null) fontFamily = "sans-serif"; } if (theme.contains("serif")) { if (noteContents != null) noteContents.setTypeface(Typeface.SERIF); if (markdownView != null) fontFamily = "serif"; } if (theme.contains("monospace")) { if (noteContents != null) noteContents.setTypeface(Typeface.MONOSPACE); if (markdownView != null) fontFamily = "monospace"; } switch (pref.getString("font_size", "normal")) { case "smallest": textSize = 12; break; case "small": textSize = 14; break; case "normal": textSize = 16; break; case "large": textSize = 18; break; case "largest": textSize = 20; break; } if (noteContents != null) noteContents.setTextSize(textSize); String css = ""; if (markdownView != null) { String topBottom = " " + Float.toString(getResources().getDimension(R.dimen.padding_top_bottom) / getResources().getDisplayMetrics().density) + "px"; String leftRight = " " + Float.toString(getResources().getDimension(R.dimen.padding_left_right) / getResources().getDisplayMetrics().density) + "px"; String fontSize = " " + Integer.toString(textSize) + "px"; String fontColor = " #" + StringUtils.remove(Integer.toHexString(textColor), "ff"); String linkColor = " #" + StringUtils.remove( Integer.toHexString(new TextView(getActivity()).getLinkTextColors().getDefaultColor()), "ff"); css = "body { " + "margin:" + topBottom + topBottom + leftRight + leftRight + "; " + "font-family:" + fontFamily + "; " + "font-size:" + fontSize + "; " + "color:" + fontColor + "; " + "}" + "a { " + "color:" + linkColor + "; " + "}"; markdownView.getSettings().setJavaScriptEnabled(false); markdownView.getSettings().setLoadsImagesAutomatically(false); markdownView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) try { startActivity(intent); } catch (ActivityNotFoundException | FileUriExposedException e) { /* Gracefully fail */ } else try { startActivity(intent); } catch (ActivityNotFoundException e) { /* Gracefully fail */ } return true; } }); } // Load note contents try { contentsOnLoad = listener.loadNote(filename); } catch (IOException e) { showToast(R.string.error_loading_note); // Add NoteListFragment or WelcomeFragment Fragment fragment; if (getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-normal")) fragment = new NoteListFragment(); else fragment = new WelcomeFragment(); getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteListFragment") .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit(); } // Set TextView contents if (noteContents != null) noteContents.setText(contentsOnLoad); if (markdownView != null) markdownView.loadMarkdown(contentsOnLoad, "data:text/css;base64," + Base64.encodeToString(css.getBytes(), Base64.DEFAULT)); // Show a toast message if this is the user's first time viewing a note final SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); firstLoad = sharedPref.getInt("first-load", 0); if (firstLoad == 0) { // Show dialog with info DialogFragment firstLoad = new FirstViewDialogFragment(); firstLoad.show(getFragmentManager(), "firstloadfragment"); // Set first-load preference to 1; we don't need to show the dialog anymore SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt("first-load", 1); editor.apply(); } // Detect single and double-taps using GestureDetector final GestureDetector detector = new GestureDetector(getActivity(), new GestureDetector.OnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; } @Override public boolean onDown(MotionEvent e) { return false; } }); detector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() { @Override public boolean onDoubleTap(MotionEvent e) { if (sharedPref.getBoolean("show_double_tap_message", true)) { SharedPreferences.Editor editor = sharedPref.edit(); editor.putBoolean("show_double_tap_message", false); editor.apply(); } Bundle bundle = new Bundle(); bundle.putString("filename", filename); Fragment fragment = new NoteEditFragment(); fragment.setArguments(bundle); getFragmentManager().beginTransaction().replace(R.id.noteViewEdit, fragment, "NoteEditFragment") .commit(); return false; } @Override public boolean onDoubleTapEvent(MotionEvent e) { return false; } @Override public boolean onSingleTapConfirmed(MotionEvent e) { if (sharedPref.getBoolean("show_double_tap_message", true) && showMessage) { showToastLong(R.string.double_tap); showMessage = false; } return false; } }); if (noteContents != null) noteContents.setOnTouchListener((v, event) -> { detector.onTouchEvent(event); return false; }); if (markdownView != null) markdownView.setOnTouchListener((v, event) -> { detector.onTouchEvent(event); return false; }); }
From source file:com.hugo.actfinder.ChatActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); //mUsername = ANONYMOUS; // Initialize Firebase Auth mFirebaseAuth = FirebaseAuth.getInstance(); mFirebaseUser = mFirebaseAuth.getCurrentUser(); if (mFirebaseUser == null) { // Not signed in, launch the Sign In activity startActivity(new Intent(this, SignInActivity.class)); finish();/*from w ww.j a v a2 s . c o m*/ return; } else { mUsername = mFirebaseUser.getDisplayName(); mPhotoUrl = mFirebaseUser.getPhotoUrl().toString(); } mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) .addApi(Auth.GOOGLE_SIGN_IN_API).build(); mProgressBar = (ProgressBar) findViewById(R.id.progressBar); mMessageRecyclerView = (RecyclerView) findViewById(R.id.messageRecyclerView); mLinearLayoutManager = new LinearLayoutManager(this); mLinearLayoutManager.setStackFromEnd(true); mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference(); mFirebaseAdapter = new FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder>(FriendlyMessage.class, R.layout.item_message, MessageViewHolder.class, mFirebaseDatabaseReference.child(MESSAGES_CHILD)) { @Override protected void populateViewHolder(MessageViewHolder viewHolder, FriendlyMessage friendlyMessage, int position) { mProgressBar.setVisibility(ProgressBar.INVISIBLE); viewHolder.messageTextView.setText(friendlyMessage.getText()); viewHolder.messengerTextView.setText(friendlyMessage.getName()); if (friendlyMessage.getPhotoUrl() == null) { viewHolder.messengerImageView.setImageDrawable( ContextCompat.getDrawable(ChatActivity.this, R.drawable.ic_account_circle_black_36dp)); } else { Glide.with(ChatActivity.this).load(friendlyMessage.getPhotoUrl()) .into(viewHolder.messengerImageView); } } }; mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { @Override public void onItemRangeInserted(int positionStart, int itemCount) { super.onItemRangeInserted(positionStart, itemCount); int friendlyMessageCount = mFirebaseAdapter.getItemCount(); int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition(); // If the recycler view is initially being loaded or the user is at the bottom of the list, scroll // to the bottom of the list to show the newly added message. if (lastVisiblePosition == -1 || (positionStart >= (friendlyMessageCount - 1) && lastVisiblePosition == (positionStart - 1))) { mMessageRecyclerView.scrollToPosition(positionStart); } } }); mMessageRecyclerView.setLayoutManager(mLinearLayoutManager); mMessageRecyclerView.setAdapter(mFirebaseAdapter); // Initialize and request AdMob ad. mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest); // Initialize Firebase Measurement. mFirebaseAnalytics = FirebaseAnalytics.getInstance(this); // Initialize Firebase Remote Config. mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance(); // Define Firebase Remote Config Settings. FirebaseRemoteConfigSettings firebaseRemoteConfigSettings = new FirebaseRemoteConfigSettings.Builder() .setDeveloperModeEnabled(true).build(); // Define default config values. Defaults are used when fetched config values are not // available. Eg: if an error occurred fetching values from the server. Map<String, Object> defaultConfigMap = new HashMap<>(); defaultConfigMap.put("friendly_msg_length", 10L); // Apply config settings and default values. mFirebaseRemoteConfig.setConfigSettings(firebaseRemoteConfigSettings); mFirebaseRemoteConfig.setDefaults(defaultConfigMap); // Fetch remote config. fetchConfig(); mMessageEditText = (EditText) findViewById(R.id.messageEditText); mMessageEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter( mSharedPreferences.getInt(CodelabPreferences.FRIENDLY_MSG_LENGTH, DEFAULT_MSG_LENGTH_LIMIT)) }); mMessageEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { if (charSequence.toString().trim().length() > 0) { mSendButton.setEnabled(true); } else { mSendButton.setEnabled(false); } } @Override public void afterTextChanged(Editable editable) { } }); mSendButton = (Button) findViewById(R.id.sendButton); mSendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(), mUsername, mPhotoUrl); mFirebaseDatabaseReference.child(MESSAGES_CHILD).push().setValue(friendlyMessage); mMessageEditText.setText(""); mFirebaseAnalytics.logEvent(MESSAGE_SENT_EVENT, null); } }); }
From source file:com.afeng.xf.widget.snackbarlight.Light.java
/** * Make a Snackbar of {@link Light#TYPE_INFO} to display a message. * The method {@link Light#make(View, CharSequence, Drawable, int, int, int)} * is called internal./*from ww w .j av a 2 s .c o m*/ * * @param view The view to find a parent from. * @param text The message to display. Formatted text is supported. * @param duration How long to show the message. * Either {@link Light#LENGTH_SHORT} or {@link Light#LENGTH_LONG}. * @return The Snackbar that will be displayed. */ public static Snackbar info(@NonNull View view, @NonNull CharSequence text, int duration) { Context context = view.getContext(); return make(view, text, // DO NOT use the resource id directly. // It should be a resolved drawable or color. ContextCompat.getDrawable(context, R.drawable.ic_info_outline_white_24dp), // getResources().getColor() is deprecated. ContextCompat.getColor(context, R.color.color_info), ContextCompat.getColor(context, android.R.color.white), duration); }
From source file:com.dm.material.dashboard.candybar.activities.CandyBarMuzeiActivity.java
private void setDividerColor(NumberPicker picker) { java.lang.reflect.Field[] pickerFields = NumberPicker.class.getDeclaredFields(); for (java.lang.reflect.Field pf : pickerFields) { if (pf.getName().equals("mSelectionDivider")) { pf.setAccessible(true);//from w w w .j av a 2 s . c o m try { pf.set(picker, ContextCompat.getDrawable(this, Preferences.getPreferences(this).isDarkTheme() ? R.drawable.numberpicker_divider_dark : R.drawable.numberpicker_divider)); } catch (Exception e) { LogUtil.e(Log.getStackTraceString(e)); } break; } } }
From source file:com.filemanager.free.ui.views.FastScroller.java
public void setPressedHandleColor(int i) { handle.setColorFilter(i);/* www . java 2s.c o m*/ StateListDrawable stateListDrawable = new StateListDrawable(); Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.fastscroller_handle_normal); Drawable drawable1 = ContextCompat.getDrawable(getContext(), R.drawable.fastscroller_handle_pressed); stateListDrawable.addState(View.PRESSED_ENABLED_STATE_SET, new InsetDrawable(drawable1, getResources().getDimensionPixelSize(R.dimen.fastscroller_track_padding), 0, 0, 0)); stateListDrawable.addState(View.EMPTY_STATE_SET, new InsetDrawable(drawable, getResources().getDimensionPixelSize(R.dimen.fastscroller_track_padding), 0, 0, 0)); this.handle.setImageDrawable(stateListDrawable); }
From source file:agricultural.nxt.agriculturalsupervision.Activity.company.CompanyAddActivity.java
@Override protected void initView() { // ?/*from w w w .j a v a 2 s . c o m*/ isFristLocation = true; toolBar.setTitle("?"); toolBar.setLeftButtonIcon(ContextCompat.getDrawable(this, R.mipmap.icon_arrow_02)); toolBar.setLeftButtonOnClickLinster(v -> finish()); sp_ikind.attachDataSource(Arrays.asList(mSpData)); sp_ikind.setSelectedIndex(0); sp_icheckstatus.attachDataSource(Arrays.asList(mSpCheck)); sp_icheckstatus.setSelectedIndex(0); photoAdapter1 = new PhotoAdapter(this, selectedPhotos1); photoAdapter2 = new PhotoAdapter(this, selectedPhotos2); recycler_view.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL)); recycler_view.setAdapter(photoAdapter1); recycler_view2.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL)); recycler_view2.setAdapter(photoAdapter2); mBaiduMap = mapview.getMap(); MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f); mBaiduMap.setMapStatus(msu); mBaiduMap.setOnMapTouchListener(this); btnselect1.setOnClickListener(this); btnselect2.setOnClickListener(this); sp_ikind.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { kind = position + ""; } @Override public void onNothingSelected(AdapterView<?> parent) { } }); cb_seed.setOnCheckedChangeListener((buttonView, isChecked) -> { if (isChecked) { sb.append("0" + ","); } }); cb_pesticide.setOnCheckedChangeListener((buttonView, isChecked) -> { if (isChecked) { sb.append("1" + ","); } }); cb_fertilizer.setOnCheckedChangeListener((buttonView, isChecked) -> { if (isChecked) { sb.append("2" + ","); } }); //? mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { //?? double latitude = latLng.latitude; double longitude = latLng.longitude; Log.i(TAG, "latitude=" + latitude + "," + "longitude=" + longitude); tv_vcgpsx.setText(longitude + ""); tv_fgpsy.setText(latitude + ""); // mBaiduMap.clear(); // Maker?? LatLng point = new LatLng(latitude, longitude); // MarkerOptionMarker MarkerOptions options = new MarkerOptions().position(point).icon(bitmap); // Marker mBaiduMap.addOverlay(options); //?? GeoCoder geoCoder = GeoCoder.newInstance(); //??????? ReverseGeoCodeOption op = new ReverseGeoCodeOption(); op.location(point); //?????(?->??) geoCoder.reverseGeoCode(op); geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() { @Override public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) { } @Override public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) { et_vcaddress.setText(reverseGeoCodeResult.getAddress()); } }); } @Override public boolean onMapPoiClick(MapPoi mapPoi) { return false; } }); // ?? initMyLocation(); OkGo.get(Constants.COMPANY_MANAGER).tag(this).execute(new StringCallback() { @Override public void onSuccess(String s, Call call, Response response) { if (s != null) { Company add = new Gson().fromJson(s, Company.class); tv_areaname.setText(add.getData().getArea().getName()); tv_vcorgname.setText(add.getData().getVcorgname()); companyId = add.getData().getId(); String type = add.getData().getIkind(); if ("0".equalsIgnoreCase(type)) { sp_ikind.setSelectedIndex(0); } else if ("1".equalsIgnoreCase(type)) { sp_ikind.setSelectedIndex(1); } else if ("2".equalsIgnoreCase(type)) { sp_ikind.setSelectedIndex(2); } List<String> onwntype = add.getData().getOwnerscopeTypes(); for (int i = 0; i < onwntype.size(); i++) { if (onwntype.get(i).equalsIgnoreCase("0")) { cb_seed.setChecked(true); } else if (onwntype.get(i).equalsIgnoreCase("1")) { cb_pesticide.setChecked(true); } else if (onwntype.get(i).equalsIgnoreCase("2")) { cb_fertilizer.setChecked(true); } } et_vccorporation.setText(add.getData().getVccorporation()); et_vcidnumber.setText(add.getData().getVcidnumber()); et_vcphone.setText(add.getData().getVcphone()); et_vcemail.setText(add.getData().getVcemail()); et_vcaddress.setText(add.getData().getVcaddress()); tv_vcgpsx.setText(add.getData().getVcgpsx()); tv_fgpsy.setText(add.getData().getFgpsy()); //? et_vcbizlicense.setText(add.getData().getVcbizlicense()); tv_cbizlicedate.setText(add.getData().getVcbizlicedate()); //?? et_vcproductlicense.setText(add.getData().getVcproductlicense()); tv_dtprodlicendate.setText(add.getData().getDtprodlicendate()); String ss = add.getData().getVcbizlicepic(); if (ss != null & !"".equals(ss)) { selectedPhotos1.add(Constants.IMG_HEAD + add.getData().getVcbizlicepic()); photoAdapter1.notifyDataSetChanged(); } if (ss != null & !"".equals(ss)) { selectedPhotos2.add(Constants.IMG_HEAD + add.getData().getVcprodlicenpic()); photoAdapter2.notifyDataSetChanged(); } } } }); // tv_cbizlicedate.setOnClickListener(v -> showTimePickDialog(tv_cbizlicedate)); tv_dtprodlicendate.setOnClickListener(v -> showTimePickDialog(tv_dtprodlicendate)); }
From source file:com.bilibili.magicasakura.widgets.AppCompatCompoundButtonHelper.java
@Override public void tint() { if (mCompoundButtonTintResId == 0 || !setSupportButtonDrawableTint(mCompoundButtonTintResId)) { Drawable drawable = mTintManager.getDrawable(mCompoundButtonResId); if (drawable == null) { drawable = mCompoundButtonResId == 0 ? null : ContextCompat.getDrawable(mView.getContext(), mCompoundButtonResId); }//from ww w.ja v a2 s .c o m setButtonDrawable(drawable); } }
From source file:com.google.samples.apps.topeka.adapter.CategoryAdapter.java
/** * Loads and tints a check mark.//from w w w .j av a 2s . com * * @return The tinted check mark */ private Drawable loadTintedDoneDrawable() { final Drawable done = ContextCompat.getDrawable(mActivity, R.drawable.ic_tick); return wrapAndTint(done, android.R.color.white); }
From source file:com.hartcode.hartweather.list.WeatherListActivity.java
@Override public boolean onMenuItemActionExpand(MenuItem item) { if (item.getItemId() == R.id.action_add) { // change fab to search button this.floatingActionButton .setImageDrawable(ContextCompat.getDrawable(this, android.R.drawable.ic_menu_search)); }// w w w .j a v a 2 s .co m return true; }
From source file:com.hitomi.circlemenu.transtion.FabTransform.java
@Override public Animator createAnimator(final ViewGroup sceneRoot, final TransitionValues startValues, final TransitionValues endValues) { if (startValues == null || endValues == null) return null; final Rect startBounds = (Rect) startValues.values.get(PROP_BOUNDS); final Rect endBounds = (Rect) endValues.values.get(PROP_BOUNDS); final boolean fromFab = endBounds.width() > startBounds.width(); final View view = endValues.view; final Rect dialogBounds = fromFab ? endBounds : startBounds; final Rect fabBounds = fromFab ? startBounds : endBounds; final Interpolator fastOutSlowInInterpolator = AnimUtils .getFastOutSlowInInterpolator(sceneRoot.getContext()); final long duration = getDuration(); final long halfDuration = duration / 2; final long twoThirdsDuration = duration * 2 / 3; if (!fromFab) { // Force measure / layout the dialog back to it'page_two original bounds view.measure(makeMeasureSpec(startBounds.width(), View.MeasureSpec.EXACTLY), makeMeasureSpec(startBounds.height(), View.MeasureSpec.EXACTLY)); view.layout(startBounds.left, startBounds.top, startBounds.right, startBounds.bottom); }//from w ww .j a v a 2s.c o m final int translationX = startBounds.centerX() - endBounds.centerX(); final int translationY = startBounds.centerY() - endBounds.centerY(); if (fromFab) { view.setTranslationX(translationX); view.setTranslationY(translationY); } // Add a color overlay to fake appearance of the FAB final ColorDrawable fabColor = new ColorDrawable(color); fabColor.setBounds(0, 0, dialogBounds.width(), dialogBounds.height()); if (!fromFab) fabColor.setAlpha(0); view.getOverlay().add(fabColor); // Add an icon overlay again to fake the appearance of the FAB final Drawable fabIcon = ContextCompat.getDrawable(sceneRoot.getContext(), icon).mutate(); final int iconLeft = (dialogBounds.width() - fabIcon.getIntrinsicWidth()) / 2; final int iconTop = (dialogBounds.height() - fabIcon.getIntrinsicHeight()) / 2; fabIcon.setBounds(iconLeft, iconTop, iconLeft + fabIcon.getIntrinsicWidth(), iconTop + fabIcon.getIntrinsicHeight()); if (!fromFab) fabIcon.setAlpha(0); view.getOverlay().add(fabIcon); // Circular clip from/to the FAB size final Animator circularReveal; if (fromFab) { circularReveal = ViewAnimationUtils.createCircularReveal(view, view.getWidth() / 2, view.getHeight() / 2, startBounds.width() / 2, (float) Math.hypot(endBounds.width() / 2, endBounds.height() / 2)); circularReveal.setInterpolator(AnimUtils.getFastOutLinearInInterpolator(sceneRoot.getContext())); } else { circularReveal = ViewAnimationUtils.createCircularReveal(view, view.getWidth() / 2, view.getHeight() / 2, (float) Math.hypot(startBounds.width() / 2, startBounds.height() / 2), endBounds.width() / 2); circularReveal.setInterpolator(AnimUtils.getLinearOutSlowInInterpolator(sceneRoot.getContext())); // Persist the end clip i.e. stay at FAB size after the reveal has run circularReveal.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { view.setOutlineProvider(new ViewOutlineProvider() { @Override public void getOutline(View view, Outline outline) { final int left = (view.getWidth() - fabBounds.width()) / 2; final int top = (view.getHeight() - fabBounds.height()) / 2; outline.setOval(left, top, left + fabBounds.width(), top + fabBounds.height()); view.setClipToOutline(true); } }); } }); } circularReveal.setDuration(duration); // Translate to end position along an arc final Animator translate = ObjectAnimator.ofFloat(view, View.TRANSLATION_X, View.TRANSLATION_Y, fromFab ? getPathMotion().getPath(translationX, translationY, 0, 0) : getPathMotion().getPath(0, 0, -translationX, -translationY)); translate.setDuration(duration); translate.setInterpolator(fastOutSlowInInterpolator); // Fade contents of non-FAB view in/out List<Animator> fadeContents = null; if (view instanceof ViewGroup) { final ViewGroup vg = ((ViewGroup) view); fadeContents = new ArrayList<>(vg.getChildCount()); for (int i = vg.getChildCount() - 1; i >= 0; i--) { final View child = vg.getChildAt(i); final Animator fade = ObjectAnimator.ofFloat(child, View.ALPHA, fromFab ? 1f : 0f); if (fromFab) { child.setAlpha(0f); } fade.setDuration(twoThirdsDuration); fade.setInterpolator(fastOutSlowInInterpolator); fadeContents.add(fade); } } // Fade in/out the fab color & icon overlays final Animator colorFade = ObjectAnimator.ofInt(fabColor, "alpha", fromFab ? 0 : 255); final Animator iconFade = ObjectAnimator.ofInt(fabIcon, "alpha", fromFab ? 0 : 255); if (!fromFab) { colorFade.setStartDelay(halfDuration); iconFade.setStartDelay(halfDuration); } colorFade.setDuration(halfDuration); iconFade.setDuration(halfDuration); colorFade.setInterpolator(fastOutSlowInInterpolator); iconFade.setInterpolator(fastOutSlowInInterpolator); // Work around issue with elevation shadows. At the end of the return transition the shared // element'page_two shadow is drawn twice (by each activity) which is jarring. This workaround // still causes the shadow to snap, but it'page_two better than seeing it double drawn. Animator elevation = null; if (!fromFab) { elevation = ObjectAnimator.ofFloat(view, View.TRANSLATION_Z, -view.getElevation()); elevation.setDuration(duration); elevation.setInterpolator(fastOutSlowInInterpolator); } // Run all animations together final AnimatorSet transition = new AnimatorSet(); transition.playTogether(circularReveal, translate, colorFade, iconFade); transition.playTogether(fadeContents); if (elevation != null) transition.play(elevation); if (fromFab) { transition.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { // Clean up view.getOverlay().clear(); } }); } return new AnimUtils.NoPauseAnimator(transition); }