android.animation.LayoutTransition

Here are the examples of the java api android.animation.LayoutTransition taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

44 Examples 7

19 Source : MainActivity.java
with MIT License
from ShaolinZhang

public clreplaced MainActivity extends AppCompatActivity {

    public static final String TAG = MainActivity.clreplaced.getName();

    private FrameLayout mContentFrameLayout;

    private ObjectAnimator mPushInAnimator;

    private ObjectAnimator mPushOutAnimator;

    private ObjectAnimator mPopInAnimator;

    private LayoutTransition mPopOutTransition;

    private Stack<SetViewWrapper> mStack;

    private TextView mreplacedleTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // When the compile and target version is higher than 22, please request the following permissions at runtime to ensure the SDK work well.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.VIBRATE, Manifest.permission.INTERNET, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.WAKE_LOCK, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.READ_PHONE_STATE }, 1);
        }
        /**
         * each time the USB from the RC is connected/disconnected,
         * the phone will prompt the user to select the app they want
         * to connect
         */
        // Intent aoaIntent = getIntent();
        // if (aoaIntent!=null) {
        // String action = aoaIntent.getAction();
        // if (action== UsbManager.ACTION_USB_ACCESSORY_ATTACHED) {
        // Intent attachedIntent=new Intent();
        // 
        // attachedIntent.setAction(DJISDKManager.USB_ACCESSORY_ATTACHED);
        // sendBroadcast(attachedIntent);
        // }
        // }
        setContentView(R.layout.activity_main);
        setupActionBar();
        mContentFrameLayout = (FrameLayout) findViewById(R.id.framelayout_content);
        initParams();
        EventBus.getDefault().register(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(DJISampleApplication.FLAG_CONNECTION_CHANGE);
        registerReceiver(mReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    private void setupActionBar() {
        ActionBar actionBar = getSupportActionBar();
        if (null != actionBar) {
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            actionBar.setCustomView(R.layout.actionbar_custom);
            mreplacedleTextView = (TextView) (actionBar.getCustomView().findViewById(R.id.replacedle_tv));
        }
    }

    private void setupInAnimations() {
        mPushInAnimator = (ObjectAnimator) AnimatorInflater.loadAnimator(this, R.animator.slide_in_right);
        mPushOutAnimator = (ObjectAnimator) AnimatorInflater.loadAnimator(this, R.animator.fade_out);
        mPopInAnimator = (ObjectAnimator) AnimatorInflater.loadAnimator(this, R.animator.fade_in);
        ObjectAnimator popOutAnimator = (ObjectAnimator) AnimatorInflater.loadAnimator(this, R.animator.slide_out_right);
        mPushOutAnimator.setStartDelay(100);
        mPopOutTransition = new LayoutTransition();
        mPopOutTransition.setAnimator(LayoutTransition.DISAPPEARING, popOutAnimator);
        mPopOutTransition.setDuration(popOutAnimator.getDuration());
    }

    private void initParams() {
        setupInAnimations();
        mStack = new Stack<SetViewWrapper>();
        View view = mContentFrameLayout.getChildAt(0);
        mStack.push(new SetViewWrapper(view, R.string.activity_component_list));
    }

    private void pushView(SetViewWrapper wrapper) {
        if (mStack.size() <= 0)
            return;
        mContentFrameLayout.setLayoutTransition(null);
        int replacedleId = wrapper.getreplacedleId();
        View showView = wrapper.getView();
        int prereplacedleId = mStack.peek().getreplacedleId();
        View preView = mStack.peek().getView();
        mStack.push(wrapper);
        mContentFrameLayout.addView(showView);
        mPushOutAnimator.setTarget(preView);
        mPushOutAnimator.start();
        mPushInAnimator.setTarget(showView);
        mPushInAnimator.setFloatValues(mContentFrameLayout.getWidth(), 0);
        mPushInAnimator.start();
        refreshreplacedle();
    }

    protected BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            refreshreplacedle();
        }
    };

    private void refreshreplacedle() {
        if (mStack.size() > 1) {
            SetViewWrapper wrapper = mStack.peek();
            mreplacedleTextView.setText(wrapper.getreplacedleId());
        } else if (mStack.size() == 1) {
            DJIBaseProduct product = DJISampleApplication.getProductInstance();
            if (product != null && product.getModel() != null) {
                mreplacedleTextView.setText("" + product.getModel().getDisplayName());
            } else {
                mreplacedleTextView.setText(R.string.app_name);
            }
        }
    }

    private void popView() {
        if (mStack.size() <= 1) {
            finish();
            return;
        }
        SetViewWrapper removeWrapper = mStack.pop();
        View showView = mStack.peek().getView();
        View removeView = removeWrapper.getView();
        int replacedleId = mStack.peek().getreplacedleId();
        int prereplacedleId = 0;
        if (mStack.size() > 1) {
            prereplacedleId = mStack.get(mStack.size() - 2).getreplacedleId();
        }
        mContentFrameLayout.setLayoutTransition(mPopOutTransition);
        mContentFrameLayout.removeView(removeView);
        mPopInAnimator.setTarget(showView);
        mPopInAnimator.start();
        refreshreplacedle();
    }

    @Override
    public void onBackPressed() {
        if (mStack.size() > 1) {
            popView();
        } else {
            super.onBackPressed();
        }
    }

    public void onEventMainThread(SetViewWrapper wrapper) {
        pushView(wrapper);
    }

    public void onEventMainThread(SetViewWrapper.Remove wrapper) {
        if (mStack.peek().getView() == wrapper.getView()) {
            popView();
        }
    }
}

19 Source : NewOperationActivity.java
with MIT License
from muun

/**
 * TODO: the animations here are sometimes dropping a couple frames due to the amount of stuff
 * we are doing on `OperationsActions::prepareOperation`. We should do something to
 * run more things on background and/or preload fees and total value.
 */
private void goToConfirmStep() {
    hideSoftKeyboard();
    resolvingSpinner.setVisibility(View.GONE);
    changeVisibility(amountSelectedViews, View.VISIBLE);
    descriptionInput.setVisibility(View.GONE);
    amountInput.setVisibility(View.GONE);
    descriptionContent.setText(descriptionInput.getText());
    changeVisibility(amountEditableViews, View.GONE);
    final LayoutTransition transition = new LayoutTransition();
    transition.setDuration(ANIMATION_DURATION_MS);
    // We only want to animate the effect that some appearing or disappearing view
    // has in other views, not the changes in the changed view itself.
    transition.disableTransitionType(APPEARING);
    transition.disableTransitionType(DISAPPEARING);
    root.setLayoutTransition(transition);
    descriptionLabel.setVisibility(View.VISIBLE);
    descriptionContent.setVisibility(View.VISIBLE);
    UiUtils.fadeIn(feeLabel);
    UiUtils.fadeIn(feeAmount);
    UiUtils.fadeIn(totalLabel);
    UiUtils.fadeIn(totalAmount);
    actionButton.setText(R.string.new_operation_confirm);
}

19 Source : LayoutAnimationsHideShow.java
with Apache License 2.0
from jiyouliang

/**
 * This application demonstrates how to use LayoutTransition to automate transition animations
 * as items are hidden or shown in a container.
 */
public clreplaced LayoutAnimationsHideShow extends Activity {

    private int numButtons = 1;

    ViewGroup container = null;

    private LayoutTransition mTransitioner;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_animations_hideshow);
        final CheckBox hideGoneCB = (CheckBox) findViewById(R.id.hideGoneCB);
        container = new LinearLayout(this);
        container.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        // Add a slew of buttons to the container. We won't add any more buttons at runtime, but
        // will just show/hide the buttons we've already created
        for (int i = 0; i < 4; ++i) {
            Button newButton = new Button(this);
            newButton.setText(String.valueOf(i));
            container.addView(newButton);
            newButton.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    v.setVisibility(hideGoneCB.isChecked() ? View.GONE : View.INVISIBLE);
                }
            });
        }
        resetTransition();
        ViewGroup parent = (ViewGroup) findViewById(R.id.parent);
        parent.addView(container);
        Button addButton = (Button) findViewById(R.id.addNewButton);
        addButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                for (int i = 0; i < container.getChildCount(); ++i) {
                    View view = (View) container.getChildAt(i);
                    view.setVisibility(View.VISIBLE);
                }
            }
        });
        CheckBox customAnimCB = (CheckBox) findViewById(R.id.customAnimCB);
        customAnimCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                long duration;
                if (isChecked) {
                    mTransitioner.setStagger(LayoutTransition.CHANGE_APPEARING, 30);
                    mTransitioner.setStagger(LayoutTransition.CHANGE_DISAPPEARING, 30);
                    setupCustomAnimations();
                    duration = 500;
                } else {
                    resetTransition();
                    duration = 300;
                }
                mTransitioner.setDuration(duration);
            }
        });
    }

    private void resetTransition() {
        mTransitioner = new LayoutTransition();
        container.setLayoutTransition(mTransitioner);
    }

    private void setupCustomAnimations() {
        // Changing while Adding
        PropertyValuesHolder pvhLeft = PropertyValuesHolder.ofInt("left", 0, 1);
        PropertyValuesHolder pvhTop = PropertyValuesHolder.ofInt("top", 0, 1);
        PropertyValuesHolder pvhRight = PropertyValuesHolder.ofInt("right", 0, 1);
        PropertyValuesHolder pvhBottom = PropertyValuesHolder.ofInt("bottom", 0, 1);
        PropertyValuesHolder pvhScaleX = PropertyValuesHolder.ofFloat("scaleX", 1f, 0f, 1f);
        PropertyValuesHolder pvhScaleY = PropertyValuesHolder.ofFloat("scaleY", 1f, 0f, 1f);
        final ObjectAnimator changeIn = ObjectAnimator.ofPropertyValuesHolder(this, pvhLeft, pvhTop, pvhRight, pvhBottom, pvhScaleX, pvhScaleY).setDuration(mTransitioner.getDuration(LayoutTransition.CHANGE_APPEARING));
        mTransitioner.setAnimator(LayoutTransition.CHANGE_APPEARING, changeIn);
        changeIn.addListener(new AnimatorListenerAdapter() {

            public void onAnimationEnd(Animator anim) {
                View view = (View) ((ObjectAnimator) anim).getTarget();
                view.setScaleX(1f);
                view.setScaleY(1f);
            }
        });
        // Changing while Removing
        Keyframe kf0 = Keyframe.ofFloat(0f, 0f);
        Keyframe kf1 = Keyframe.ofFloat(.9999f, 360f);
        Keyframe kf2 = Keyframe.ofFloat(1f, 0f);
        PropertyValuesHolder pvhRotation = PropertyValuesHolder.ofKeyframe("rotation", kf0, kf1, kf2);
        final ObjectAnimator changeOut = ObjectAnimator.ofPropertyValuesHolder(this, pvhLeft, pvhTop, pvhRight, pvhBottom, pvhRotation).setDuration(mTransitioner.getDuration(LayoutTransition.CHANGE_DISAPPEARING));
        mTransitioner.setAnimator(LayoutTransition.CHANGE_DISAPPEARING, changeOut);
        changeOut.addListener(new AnimatorListenerAdapter() {

            public void onAnimationEnd(Animator anim) {
                View view = (View) ((ObjectAnimator) anim).getTarget();
                view.setRotation(0f);
            }
        });
        // Adding
        ObjectAnimator animIn = ObjectAnimator.ofFloat(null, "rotationY", 90f, 0f).setDuration(mTransitioner.getDuration(LayoutTransition.APPEARING));
        mTransitioner.setAnimator(LayoutTransition.APPEARING, animIn);
        animIn.addListener(new AnimatorListenerAdapter() {

            public void onAnimationEnd(Animator anim) {
                View view = (View) ((ObjectAnimator) anim).getTarget();
                view.setRotationY(0f);
            }
        });
        // Removing
        ObjectAnimator animOut = ObjectAnimator.ofFloat(null, "rotationX", 0f, 90f).setDuration(mTransitioner.getDuration(LayoutTransition.DISAPPEARING));
        mTransitioner.setAnimator(LayoutTransition.DISAPPEARING, animOut);
        animOut.addListener(new AnimatorListenerAdapter() {

            public void onAnimationEnd(Animator anim) {
                View view = (View) ((ObjectAnimator) anim).getTarget();
                view.setRotationX(0f);
            }
        });
    }
}

19 Source : AnimateLayoutChangeDetector.java
with Apache License 2.0
from IslamKhSh

private static boolean hasRunningChangingLayoutTransition(View view) {
    if (view instanceof ViewGroup) {
        ViewGroup viewGroup = (ViewGroup) view;
        LayoutTransition layoutTransition = viewGroup.getLayoutTransition();
        if (layoutTransition != null && layoutTransition.isChangingLayout()) {
            return true;
        }
        int childCount = viewGroup.getChildCount();
        for (int i = 0; i < childCount; i++) {
            if (hasRunningChangingLayoutTransition(viewGroup.getChildAt(i))) {
                return true;
            }
        }
    }
    return false;
}

19 Source : JustBar.java
with Apache License 2.0
from Hamadakram

private void init() {
    LayoutTransition lt = new LayoutTransition();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        lt.disableTransitionType(LayoutTransition.DISAPPEARING);
    }
    setLayoutTransition(lt);
    setOrientation(HORIZONTAL);
    setGravity(Gravity.CENTER_VERTICAL);
}

19 Source : CoolMenu.java
with Apache License 2.0
from crazysunj

@Override
public void setLayoutTransition(LayoutTransition transition) {
    super.setLayoutTransition(transition);
}

19 Source : ViewGroupUtilsApi14.java
with Apache License 2.0
from covidsafewatch

clreplaced ViewGroupUtilsApi14 {

    private static final int LAYOUT_TRANSITION_CHANGING = 4;

    private static final String TAG = "ViewGroupUtilsApi14";

    private static Method sCancelMethod;

    private static boolean sCancelMethodFetched;

    private static LayoutTransition sEmptyLayoutTransition;

    private static Field sLayoutSuppressedField;

    private static boolean sLayoutSuppressedFieldFetched;

    /* JADX WARNING: Removed duplicated region for block: B:34:0x0081  */
    /* JADX WARNING: Removed duplicated region for block: B:37:0x008e  */
    /* JADX WARNING: Removed duplicated region for block: B:40:? A[RETURN, SYNTHETIC] */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    static void suppressLayout(android.view.ViewGroup r5, boolean r6) {
        /*
            android.animation.LayoutTransition r0 = sEmptyLayoutTransition
            r1 = 1
            r2 = 0
            r3 = 0
            if (r0 != 0) goto L_0x0028
            androidx.transition.ViewGroupUtilsApi14$1 r0 = new androidx.transition.ViewGroupUtilsApi14$1
            r0.<init>()
            sEmptyLayoutTransition = r0
            r4 = 2
            r0.setAnimator(r4, r3)
            android.animation.LayoutTransition r0 = sEmptyLayoutTransition
            r0.setAnimator(r2, r3)
            android.animation.LayoutTransition r0 = sEmptyLayoutTransition
            r0.setAnimator(r1, r3)
            android.animation.LayoutTransition r0 = sEmptyLayoutTransition
            r4 = 3
            r0.setAnimator(r4, r3)
            android.animation.LayoutTransition r0 = sEmptyLayoutTransition
            r4 = 4
            r0.setAnimator(r4, r3)
        L_0x0028:
            if (r6 == 0) goto L_0x0048
            android.animation.LayoutTransition r6 = r5.getLayoutTransition()
            if (r6 == 0) goto L_0x0042
            boolean r0 = r6.isRunning()
            if (r0 == 0) goto L_0x0039
            cancelLayoutTransition(r6)
        L_0x0039:
            android.animation.LayoutTransition r0 = sEmptyLayoutTransition
            if (r6 == r0) goto L_0x0042
            int r0 = androidx.transition.R.id.transition_layout_save
            r5.setTag(r0, r6)
        L_0x0042:
            android.animation.LayoutTransition r6 = sEmptyLayoutTransition
            r5.setLayoutTransition(r6)
            goto L_0x0096
        L_0x0048:
            r5.setLayoutTransition(r3)
            boolean r6 = sLayoutSuppressedFieldFetched
            java.lang.String r0 = "ViewGroupUtilsApi14"
            if (r6 != 0) goto L_0x0066
            java.lang.Clreplaced<android.view.ViewGroup> r6 = android.view.ViewGroup.clreplaced
            java.lang.String r4 = "mLayoutSuppressed"
            java.lang.reflect.Field r6 = r6.getDeclaredField(r4)     // Catch:{ NoSuchFieldException -> 0x005f }
            sLayoutSuppressedField = r6     // Catch:{ NoSuchFieldException -> 0x005f }
            r6.setAccessible(r1)     // Catch:{ NoSuchFieldException -> 0x005f }
            goto L_0x0064
        L_0x005f:
            java.lang.String r6 = "Failed to access mLayoutSuppressed field by reflection"
            android.util.Log.i(r0, r6)
        L_0x0064:
            sLayoutSuppressedFieldFetched = r1
        L_0x0066:
            java.lang.reflect.Field r6 = sLayoutSuppressedField
            if (r6 == 0) goto L_0x007f
            boolean r6 = r6.getBoolean(r5)     // Catch:{ IllegalAccessException -> 0x007a }
            if (r6 == 0) goto L_0x0078
            java.lang.reflect.Field r1 = sLayoutSuppressedField     // Catch:{ IllegalAccessException -> 0x0076 }
            r1.setBoolean(r5, r2)     // Catch:{ IllegalAccessException -> 0x0076 }
            goto L_0x0078
        L_0x0076:
            r2 = r6
            goto L_0x007a
        L_0x0078:
            r2 = r6
            goto L_0x007f
        L_0x007a:
            java.lang.String r6 = "Failed to get mLayoutSuppressed field by reflection"
            android.util.Log.i(r0, r6)
        L_0x007f:
            if (r2 == 0) goto L_0x0084
            r5.requestLayout()
        L_0x0084:
            int r6 = androidx.transition.R.id.transition_layout_save
            java.lang.Object r6 = r5.getTag(r6)
            android.animation.LayoutTransition r6 = (android.animation.LayoutTransition) r6
            if (r6 == 0) goto L_0x0096
            int r0 = androidx.transition.R.id.transition_layout_save
            r5.setTag(r0, r3)
            r5.setLayoutTransition(r6)
        L_0x0096:
            return
        */
        throw new UnsupportedOperationException("Method not decompiled: androidx.transition.ViewGroupUtilsApi14.suppressLayout(android.view.ViewGroup, boolean):void");
    }

    private static void cancelLayoutTransition(LayoutTransition layoutTransition) {
        if (!sCancelMethodFetched) {
            try {
                Method declaredMethod = LayoutTransition.clreplaced.getDeclaredMethod("cancel", new Clreplaced[0]);
                sCancelMethod = declaredMethod;
                declaredMethod.setAccessible(true);
            } catch (NoSuchMethodException unused) {
                Log.i(TAG, "Failed to access cancel method by reflection");
            }
            sCancelMethodFetched = true;
        }
        Method method = sCancelMethod;
        if (method != null) {
            try {
                method.invoke(layoutTransition, new Object[0]);
            } catch (IllegalAccessException unused2) {
                Log.i(TAG, "Failed to access cancel method by reflection");
            } catch (InvocationTargetException unused3) {
                Log.i(TAG, "Failed to invoke cancel method by reflection");
            }
        }
    }

    private ViewGroupUtilsApi14() {
    }
}

19 Source : FragmentContainerView.java
with Apache License 2.0
from covidsafewatch

public void setLayoutTransition(LayoutTransition layoutTransition) {
    if (Build.VERSION.SDK_INT < 18) {
        super.setLayoutTransition(layoutTransition);
        return;
    }
    throw new UnsupportedOperationException("FragmentContainerView does not support Layout Transitions or animateLayoutChanges=\"true\".");
}

19 Source : ViewGroupUtilsApi14.java
with Apache License 2.0
from androidx

clreplaced ViewGroupUtilsApi14 {

    private static final String TAG = "ViewGroupUtilsApi14";

    private static final int LAYOUT_TRANSITION_CHANGING = 4;

    private static LayoutTransition sEmptyLayoutTransition;

    private static Field sLayoutSuppressedField;

    private static boolean sLayoutSuppressedFieldFetched;

    private static Method sCancelMethod;

    private static boolean sCancelMethodFetched;

    static void suppressLayout(@NonNull ViewGroup group, boolean suppress) {
        // Prepare the empty LayoutTransition
        if (sEmptyLayoutTransition == null) {
            sEmptyLayoutTransition = new LayoutTransition() {

                @Override
                public boolean isChangingLayout() {
                    return true;
                }
            };
            sEmptyLayoutTransition.setAnimator(LayoutTransition.APPEARING, null);
            sEmptyLayoutTransition.setAnimator(LayoutTransition.CHANGE_APPEARING, null);
            sEmptyLayoutTransition.setAnimator(LayoutTransition.CHANGE_DISAPPEARING, null);
            sEmptyLayoutTransition.setAnimator(LayoutTransition.DISAPPEARING, null);
            sEmptyLayoutTransition.setAnimator(LAYOUT_TRANSITION_CHANGING, null);
        }
        if (suppress) {
            // Save the current LayoutTransition
            final LayoutTransition layoutTransition = group.getLayoutTransition();
            if (layoutTransition != null) {
                if (layoutTransition.isRunning()) {
                    cancelLayoutTransition(layoutTransition);
                }
                if (layoutTransition != sEmptyLayoutTransition) {
                    group.setTag(R.id.transition_layout_save, layoutTransition);
                }
            }
            // Suppress the layout
            group.setLayoutTransition(sEmptyLayoutTransition);
        } else {
            // Thaw the layout suppression
            group.setLayoutTransition(null);
            // Request layout if necessary
            if (!sLayoutSuppressedFieldFetched) {
                try {
                    sLayoutSuppressedField = ViewGroup.clreplaced.getDeclaredField("mLayoutSuppressed");
                    sLayoutSuppressedField.setAccessible(true);
                } catch (NoSuchFieldException e) {
                    Log.i(TAG, "Failed to access mLayoutSuppressed field by reflection");
                }
                sLayoutSuppressedFieldFetched = true;
            }
            boolean layoutSuppressed = false;
            if (sLayoutSuppressedField != null) {
                try {
                    layoutSuppressed = sLayoutSuppressedField.getBoolean(group);
                    if (layoutSuppressed) {
                        sLayoutSuppressedField.setBoolean(group, false);
                    }
                } catch (IllegalAccessException e) {
                    Log.i(TAG, "Failed to get mLayoutSuppressed field by reflection");
                }
            }
            if (layoutSuppressed) {
                group.requestLayout();
            }
            // Restore the saved LayoutTransition
            final LayoutTransition layoutTransition = (LayoutTransition) group.getTag(R.id.transition_layout_save);
            if (layoutTransition != null) {
                group.setTag(R.id.transition_layout_save, null);
                group.setLayoutTransition(layoutTransition);
            }
        }
    }

    /**
     * Note, this is only called on API 17 and older.
     */
    @SuppressLint("SoonBlockedPrivateApi")
    private static void cancelLayoutTransition(LayoutTransition t) {
        if (!sCancelMethodFetched) {
            try {
                sCancelMethod = LayoutTransition.clreplaced.getDeclaredMethod("cancel");
                sCancelMethod.setAccessible(true);
            } catch (NoSuchMethodException e) {
                Log.i(TAG, "Failed to access cancel method by reflection");
            }
            sCancelMethodFetched = true;
        }
        if (sCancelMethod != null) {
            try {
                sCancelMethod.invoke(t);
            } catch (IllegalAccessException e) {
                Log.i(TAG, "Failed to access cancel method by reflection");
            } catch (InvocationTargetException e) {
                Log.i(TAG, "Failed to invoke cancel method by reflection");
            }
        }
    }

    private ViewGroupUtilsApi14() {
    }
}

19 Source : FragmentContainerView.java
with Apache License 2.0
from androidx

/**
 * When called, this method throws a {@link UnsupportedOperationException} on APIs above 17.
 * On APIs 17 and below, it calls {@link FrameLayout#setLayoutTransition(LayoutTransition)}
 * This can be called either explicitly, or implicitly by setting animateLayoutChanges to
 * <code>true</code>.
 *
 * <p>View animations and transitions are disabled for FragmentContainerView for APIs above 17.
 * Use {@link FragmentTransaction#setCustomAnimations(int, int, int, int)} and
 * {@link FragmentTransaction#setTransition(int)}.
 *
 * @param transition The LayoutTransition object that will animated changes in layout. A value
 * of <code>null</code> means no transition will run on layout changes.
 * @attr ref android.R.styleable#ViewGroup_animateLayoutChanges
 */
@Override
public void setLayoutTransition(@Nullable LayoutTransition transition) {
    if (Build.VERSION.SDK_INT < 18) {
        // Transitions on APIs below 18 are using an empty LayoutTransition as a replacement
        // for suppressLayout(true) and null LayoutTransition to then unsuppress it. If the
        // API is below 18, we should allow FrameLayout to handle this call.
        super.setLayoutTransition(transition);
        return;
    }
    throw new UnsupportedOperationException("FragmentContainerView does not support Layout Transitions or " + "animateLayoutChanges=\"true\".");
}

19 Source : CardStreamLinearLayout.java
with Apache License 2.0
from android

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setCardStreamAnimator(CardStreamAnimator animators) {
    if (animators == null)
        mAnimators = new CardStreamAnimator.EmptyAnimator();
    else
        mAnimators = animators;
    LayoutTransition layoutTransition = getLayoutTransition();
    if (layoutTransition != null) {
        layoutTransition.setAnimator(LayoutTransition.APPEARING, mAnimators.getAppearingAnimator(getContext()));
        layoutTransition.setAnimator(LayoutTransition.DISAPPEARING, mAnimators.getDisappearingAnimator(getContext()));
    }
}

19 Source : CardStreamLinearLayout.java
with Apache License 2.0
from android

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    super.onLayout(changed, l, t, r, b);
    Log.d(TAG, "onLayout: " + changed);
    if (changed && !mLayouted) {
        mLayouted = true;
        ObjectAnimator animator;
        LayoutTransition layoutTransition = new LayoutTransition();
        animator = mAnimators.getDisappearingAnimator(getContext());
        layoutTransition.setAnimator(LayoutTransition.DISAPPEARING, animator);
        animator = mAnimators.getAppearingAnimator(getContext());
        layoutTransition.setAnimator(LayoutTransition.APPEARING, animator);
        layoutTransition.addTransitionListener(mTransitionListener);
        if (animator != null)
            layoutTransition.setDuration(animator.getDuration());
        setLayoutTransition(layoutTransition);
        if (mShowInitialAnimation)
            runInitialAnimations();
        if (mFirstVisibleCardTag != null) {
            scrollToCard(mFirstVisibleCardTag);
            mFirstVisibleCardTag = null;
        }
    }
}

19 Source : NiboPlacesAutoCompleteSearchView.java
with MIT License
from aliumujib

private void setUpLayoutTransition() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        RelativeLayout searchRoot = (RelativeLayout) findViewById(R.id.search_root);
        LayoutTransition layoutTransition = new LayoutTransition();
        layoutTransition.setDuration(DURATION_LAYOUT_TRANSITION);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
            // layoutTransition.enableTransitionType(LayoutTransition.CHANGING);
            layoutTransition.enableTransitionType(LayoutTransition.CHANGE_DISAPPEARING);
            layoutTransition.setStartDelay(LayoutTransition.CHANGING, 0);
        }
        layoutTransition.setStartDelay(LayoutTransition.CHANGE_DISAPPEARING, 0);
        mSearchCardView.setLayoutTransition(layoutTransition);
    }
}

18 Source : ChannelSetupFragment.java
with Apache License 2.0
from zaclimon

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(getLayoutResourceId(), container, false);
    // Make sure this view is focused
    view.requestFocus();
    mProgressBar = (ProgressBar) view.findViewById(R.id.tune_progress);
    mScanningMessage = (TextView) view.findViewById(R.id.tune_description);
    mreplacedle = (TextView) view.findViewById(R.id.tune_replacedle);
    mBadge = (ImageView) view.findViewById(R.id.tune_icon);
    mChannelHolder = view.findViewById(R.id.channel_holder);
    mCancelButton = (Button) view.findViewById(R.id.tune_cancel);
    ListView channelList = (ListView) view.findViewById(R.id.channel_list);
    mAdapter = new ChannelAdapter();
    channelList.setAdapter(mAdapter);
    channelList.setOnItemClickListener(null);
    ViewGroup progressHolder = (ViewGroup) view.findViewById(R.id.progress_holder);
    LayoutTransition transition = new LayoutTransition();
    transition.enableTransitionType(LayoutTransition.CHANGING);
    progressHolder.setLayoutTransition(transition);
    mCancelButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            finishScan();
        }
    });
    mSyncStatusChangedReceiver = new SyncStatusBroadcastReceiver(getInputId(), this);
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mSyncStatusChangedReceiver, new IntentFilter(EpgSyncJobService.ACTION_SYNC_STATUS_CHANGED));
    mChannelScanLayout = view;
    setChannelListVisibility(false);
    setBackgroundColor(getResources().getColor(android.R.color.holo_blue_dark));
    return view;
}

18 Source : ContentEditor.java
with Apache License 2.0
from scatl

/**
 * author: sca_tl
 * description: 图文混排编辑器,改自于:https://github.com/scatl/XRichText
 */
public clreplaced ContentEditor extends ScrollView {

    // edittext常规padding是10dp
    private static final int EDIT_TEXT_PADDING = 10;

    // 文本
    public static final int CONTENT_TYPE_TEXT = 0;

    // 图片
    public static final int CONTENT_TYPE_IMAGE = 1;

    // 新生的view都会打一个tag,对每个view来说,这个tag是唯一的。
    private int viewTagIndex = 1;

    // 这个是所有子view的容器,scrollView内部的唯一一个ViewGroup
    private LinearLayout rootLayout;

    private LayoutInflater inflater;

    // 所有EditText的软键盘监听器
    private OnKeyListener keyListener;

    // 图片右上角删除按钮监听器
    private OnClickListener btnListener;

    // 所有EditText的焦点监听listener
    private OnFocusChangeListener focusListener;

    // 最近被聚焦的EditText
    private EditText lastFocusEdit;

    // 只在图片View添加或remove时,触发transition动画
    private LayoutTransition mTransitioner;

    // 
    private int editNormalPadding = 0;

    private int disappearingImageIndex = 0;

    // 图片地址集合
    private ArrayList<String> imagePaths;

    /**
     * 自定义属性 *
     */
    // 插入的图片高度
    private int imageHeight = 600;

    // 两张相邻图片间距
    private int imageBottom = 10;

    // 文字相关属性,初始提示信息,文字大小和颜色
    private String textInitHint = "请输入内容";

    private String textHint = "请输入内容";

    private int textSize = 17;

    private int textColor = getContext().getColor(R.color.text_color);

    private int textLineSpace = 10;

    // 删除图片的接口
    private OnRtImageDeleteListener onRtImageDeleteListener;

    private OnRtImageClickListener onRtImageClickListener;

    public ContentEditor(Context context) {
        this(context, null);
    }

    public ContentEditor(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ContentEditor(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        imagePaths = new ArrayList<>();
        inflater = LayoutInflater.from(context);
        // 1. 初始化allLayout
        rootLayout = new LinearLayout(context);
        rootLayout.setOrientation(LinearLayout.VERTICAL);
        // 禁止载入动画
        setupLayoutTransitions();
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        // 设置间距,防止生成图片时文字太靠边,不能用margin,否则有黑边
        rootLayout.setPadding(0, 15, 0, 15);
        addView(rootLayout, layoutParams);
        // 2. 初始化键盘退格监听
        // 主要用来处理点击回删按钮时,view的一些列合并操作
        keyListener = new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
                    EditText edit = (EditText) v;
                    onBackspacePress(edit);
                }
                return false;
            }
        };
        // 3. 图片删除处理
        btnListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (v instanceof RoundImageView) {
                    RoundImageView imageView = (RoundImageView) v;
                    // 开放图片点击接口
                    if (onRtImageClickListener != null) {
                        onRtImageClickListener.onRtImageClick(imageView, imageView.getAbsolutePath());
                    }
                } else if (v instanceof ImageView) {
                    RelativeLayout parentView = (RelativeLayout) v.getParent();
                    onImageCloseClick(parentView);
                }
            }
        };
        focusListener = new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    lastFocusEdit = (EditText) v;
                }
            }
        };
        LinearLayout.LayoutParams firstEditParam = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        EditText firstEdit = createEditText(textInitHint, CommonUtil.dip2px(context, EDIT_TEXT_PADDING));
        rootLayout.addView(firstEdit, firstEditParam);
        lastFocusEdit = firstEdit;
    }

    /**
     * author: sca_tl
     * description: 回退键处理
     */
    private void onBackspacePress(EditText editTxt) {
        try {
            int startSelection = editTxt.getSelectionStart();
            // 只有在光标已经顶到文本输入框的最前方,在判定是否删除之前的图片,或两个View合并
            if (startSelection == 0) {
                int editIndex = rootLayout.indexOfChild(editTxt);
                // 如果editIndex-1<0,则返回的是null
                View preView = rootLayout.getChildAt(editIndex - 1);
                if (null != preView) {
                    if (preView instanceof RelativeLayout) {
                        // 光标EditText的上一个view对应的是图片
                        onImageCloseClick(preView);
                    } else if (preView instanceof EditText) {
                        // 光标EditText的上一个view对应的还是文本框EditText
                        String str1 = editTxt.getText().toString();
                        EditText preEdit = (EditText) preView;
                        String str2 = preEdit.getText().toString();
                        // 合并文本view时,不需要transition动画
                        rootLayout.setLayoutTransition(null);
                        rootLayout.removeView(editTxt);
                        // 恢复transition动画
                        rootLayout.setLayoutTransition(mTransitioner);
                        // 文本合并
                        preEdit.setText(String.valueOf(str2 + str1));
                        preEdit.requestFocus();
                        preEdit.setSelection(str2.length(), str2.length());
                        lastFocusEdit = preEdit;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * author: sca_tl
     * description: 处理图片叉掉的点击事件
     * @param view 整个image对应的relativeLayout view
     */
    private void onImageCloseClick(View view) {
        try {
            if (!mTransitioner.isRunning()) {
                disappearingImageIndex = rootLayout.indexOfChild(view);
                // 删除编辑器里的图片
                List<EditData> dataList = buildEditorData();
                EditData editData = dataList.get(disappearingImageIndex);
                if (editData.imagePath != null) {
                    if (onRtImageDeleteListener != null) {
                        onRtImageDeleteListener.onRtImageDelete(editData.imagePath);
                    }
                    imagePaths.remove(editData.imagePath);
                }
                rootLayout.removeView(view);
                // 合并上下EditText内容
                mergeEditText();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清空所有布局
     */
    public void clearAllLayout() {
        rootLayout.removeAllViews();
    }

    /**
     * 获取索引位置
     */
    public int getLastIndex() {
        return rootLayout.getChildCount();
    }

    /**
     * author: sca_tl
     * description: 生成文本输入框
     */
    public EditText createEditText(String hint, int paddingTop) {
        EditText editText = (EditText) inflater.inflate(R.layout.view_content_editor_edittext, null);
        editText.setOnKeyListener(keyListener);
        editText.setTag(viewTagIndex++);
        editText.setPadding(editNormalPadding, paddingTop, editNormalPadding, paddingTop);
        editText.setHint(hint);
        editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
        editText.setTextColor(textColor);
        editText.setLineSpacing(textLineSpace, 1.0f);
        editText.setOnFocusChangeListener(focusListener);
        return editText;
    }

    /**
     * author: sca_tl
     * description: 生成图片View
     */
    private RelativeLayout createImageLayout() {
        RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.view_content_editor_imageview, null);
        layout.setTag(viewTagIndex++);
        View closeView = layout.findViewById(R.id.content_editor_img_close);
        closeView.setTag(layout.getTag());
        closeView.setOnClickListener(btnListener);
        RoundImageView imageView = layout.findViewById(R.id.content_editor_imageView);
        imageView.setOnClickListener(btnListener);
        return layout;
    }

    /**
     * 根据绝对路径添加view
     */
    public void insertImage(String imagePath, int width) {
        if (TextUtils.isEmpty(imagePath)) {
            return;
        }
        Bitmap bmp = getScaledBitmap(imagePath, width);
        insertImage(bmp, imagePath);
    }

    /**
     * author: sca_tl
     * description: 插入图片
     */
    public void insertImage(Bitmap bitmap, String imagePath) {
        // bitmap == null时,可能是网络图片,不能做限制
        if (TextUtils.isEmpty(imagePath)) {
            return;
        }
        try {
            // lastFocusEdit获取焦点的EditText
            String lastEditStr = lastFocusEdit.getText().toString();
            // 获取光标所在位置
            int cursorIndex = lastFocusEdit.getSelectionStart();
            // 获取光标前面的字符串
            String editStr1 = lastEditStr.substring(0, cursorIndex).trim();
            // 获取光标后的字符串
            String editStr2 = lastEditStr.substring(cursorIndex).trim();
            // 获取焦点的EditText所在位置
            int lastEditIndex = rootLayout.indexOfChild(lastFocusEdit);
            if (lastEditStr.length() == 0) {
                // 如果当前获取焦点的EditText为空,直接在EditText下方插入图片,并且插入空的EditText
                addEditTextAtIndex(lastEditIndex + 1, "");
                addImageViewAtIndex(lastEditIndex + 1, bitmap, imagePath);
            } else if (editStr1.length() == 0) {
                // 如果光标已经顶在了editText的最前面,则直接插入图片,并且EditText下移即可
                addImageViewAtIndex(lastEditIndex, bitmap, imagePath);
                // 同时插入一个空的EditText,防止插入多张图片无法写文字
                addEditTextAtIndex(lastEditIndex + 1, "");
            } else if (editStr2.length() == 0) {
                // 如果光标已经顶在了editText的最末端,则需要添加新的imageView和EditText
                addEditTextAtIndex(lastEditIndex + 1, "");
                addImageViewAtIndex(lastEditIndex + 1, bitmap, imagePath);
            } else {
                // 如果光标已经顶在了editText的最中间,则需要分割字符串,分割成两个EditText,并在两个EditText中间插入图片
                // 把光标前面的字符串保留,设置给当前获得焦点的EditText(此为分割出来的第一个EditText)
                lastFocusEdit.setText(editStr1);
                // 把光标后面的字符串放在新创建的EditText中(此为分割出来的第二个EditText)
                addEditTextAtIndex(lastEditIndex + 1, editStr2);
                // 在第二个EditText的位置插入一个空的EditText,以便连续插入多张图片时,有空间写文字,第二个EditText下移
                addEditTextAtIndex(lastEditIndex + 1, "");
                // 在空的EditText的位置插入图片布局,空的EditText下移
                addImageViewAtIndex(lastEditIndex + 1, bitmap, imagePath);
            }
            // hideKeyBoard();
            CommonUtil.hideSoftKeyboard(getContext(), lastFocusEdit);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * author: sca_tl
     * description: 在特定位置插入EditText
     * @param index 位置
     * @param editStr EditText显示的文字
     */
    public void addEditTextAtIndex(final int index, CharSequence editStr) {
        try {
            EditText editText2 = createEditText(textHint, EDIT_TEXT_PADDING);
            if (!TextUtils.isEmpty(editStr)) {
                // 判断插入的字符串是否为空,如果没有内容则显示hint提示信息
                editText2.setText(editStr);
            }
            editText2.setOnFocusChangeListener(focusListener);
            // 请注意此处,EditText添加、或删除不触动Transition动画
            rootLayout.setLayoutTransition(null);
            rootLayout.addView(editText2, index);
            // remove之后恢复transition动画
            rootLayout.setLayoutTransition(mTransitioner);
            // 插入新的EditText之后,修改lastFocusEdit的指向
            lastFocusEdit = editText2;
            lastFocusEdit.requestFocus();
            lastFocusEdit.setSelection(editStr.length(), editStr.length());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * author: sca_tl
     * description: 在光标处插入文字
     */
    public void insertText(String text) {
        lastFocusEdit.getText().insert(lastFocusEdit.getSelectionStart(), text);
    }

    /**
     * author: sca_tl
     * description: 在光标处插入表情
     * @param emotion_path 表情路径,表情文件名[s_123]需要改成河畔服务器可识别的[s:123]
     */
    public void insertEmotion(String emotion_path) {
        String emotion_name = emotion_path.substring(emotion_path.lastIndexOf("/") + 1).replace("_", ":").replace(".gif", "");
        SpannableString spannableString = new SpannableString(emotion_name);
        Bitmap bitmap = null;
        try {
            String rePath = emotion_path.replace("file:///android_replacedet/", "");
            InputStream is = getResources().getreplacedets().open(rePath);
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Drawable drawable = ImageUtil.bitmap2Drawable(bitmap);
        drawable.setBounds(10, 10, 80, 80);
        ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BOTTOM);
        spannableString.setSpan(imageSpan, 0, emotion_name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        lastFocusEdit.getText().insert(lastFocusEdit.getSelectionStart(), spannableString);
    }

    /**
     * author: sca_tl
     * description: 在特定位置添加ImageView
     */
    public void addImageViewAtIndex(final int index, Bitmap bmp, String imagePath) {
        if (TextUtils.isEmpty(imagePath)) {
            return;
        }
        try {
            imagePaths.add(imagePath);
            RelativeLayout imageLayout = createImageLayout();
            RoundImageView imageView = imageLayout.findViewById(R.id.content_editor_imageView);
            Glide.with(getContext()).load(imagePath).into(imageView);
            imageView.setAbsolutePath(imagePath);
            // 裁剪居中
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, imageHeight);
            lp.bottomMargin = imageBottom;
            imageView.setLayoutParams(lp);
            Glide.with(getContext()).load(imagePath).into(imageView);
            rootLayout.addView(imageLayout, index);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * author: sca_tl
     * description: 在特定位置添加ImageView
     */
    public void addImageViewAtIndex(final int index, final String imagePath) {
        if (TextUtils.isEmpty(imagePath)) {
            return;
        }
        try {
            imagePaths.add(imagePath);
            RelativeLayout imageLayout = createImageLayout();
            final RoundImageView imageView = imageLayout.findViewById(R.id.content_editor_imageView);
            imageView.setAbsolutePath(imagePath);
            // 裁剪居中
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, // 固定图片高度,记得设置裁剪剧中
            imageHeight);
            lp.bottomMargin = imageBottom;
            imageView.setLayoutParams(lp);
            Glide.with(getContext()).load(imagePath).into(imageView);
            rootLayout.addView(imageLayout, index);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * author: sca_tl
     * description: 根据view的宽度,动态缩放bitmap尺寸
     * @param width view的宽度
     */
    public Bitmap getScaledBitmap(String filePath, int width) {
        if (TextUtils.isEmpty(filePath)) {
            return null;
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        try {
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(filePath, options);
            int sampleSize = options.outWidth > width ? options.outWidth / width + 1 : 1;
            options.inJustDecodeBounds = false;
            options.inSampleSize = sampleSize;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return BitmapFactory.decodeFile(filePath, options);
    }

    /**
     * 初始化transition动画
     */
    private void setupLayoutTransitions() {
        mTransitioner = new LayoutTransition();
        rootLayout.setLayoutTransition(mTransitioner);
        mTransitioner.addTransitionListener(new LayoutTransition.TransitionListener() {

            @Override
            public void startTransition(LayoutTransition transition, ViewGroup container, View view, int transitionType) {
            }

            @Override
            public void endTransition(LayoutTransition transition, ViewGroup container, View view, int transitionType) {
                if (!transition.isRunning() && transitionType == LayoutTransition.CHANGE_DISAPPEARING) {
                    // transition动画结束,合并EditText
                    mergeEditText();
                }
            }
        });
        mTransitioner.setDuration(300);
    }

    /**
     * 图片删除的时候,如果上下方都是EditText,则合并处理
     */
    private void mergeEditText() {
        try {
            View preView = rootLayout.getChildAt(disappearingImageIndex - 1);
            View nextView = rootLayout.getChildAt(disappearingImageIndex);
            if (preView instanceof EditText && nextView instanceof EditText) {
                EditText preEdit = (EditText) preView;
                EditText nextEdit = (EditText) nextView;
                String str1 = preEdit.getText().toString();
                String str2 = nextEdit.getText().toString();
                String mergeText = "";
                if (str2.length() > 0) {
                    mergeText = str1 + "\n" + str2;
                } else {
                    mergeText = str1;
                }
                rootLayout.setLayoutTransition(null);
                rootLayout.removeView(nextEdit);
                preEdit.setText(mergeText);
                preEdit.requestFocus();
                preEdit.setSelection(str1.length(), str1.length());
                rootLayout.setLayoutTransition(mTransitioner);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * author: sca_tl
     * description: 生成编辑数据
     */
    public List<EditData> buildEditorData() {
        List<EditData> dataList = new ArrayList<>();
        try {
            for (int index = 0; index < rootLayout.getChildCount(); index++) {
                View itemView = rootLayout.getChildAt(index);
                EditData itemData = new EditData();
                if (itemView instanceof EditText) {
                    // 是文本
                    EditText item = (EditText) itemView;
                    itemData.inputStr = item.getText().toString();
                    itemData.content_type = CONTENT_TYPE_TEXT;
                } else if (itemView instanceof RelativeLayout) {
                    // 是图片
                    RoundImageView item = itemView.findViewById(R.id.content_editor_imageView);
                    itemData.imagePath = item.getAbsolutePath();
                    itemData.content_type = CONTENT_TYPE_IMAGE;
                }
                dataList.add(itemData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataList;
    }

    /**
     * author: sca_tl
     * description: 编辑器是否为空
     */
    public boolean isEditorEmpty() {
        return TextUtils.isEmpty(lastFocusEdit.getText()) && imagePaths.size() == 0;
    }

    /**
     * author: sca_tl
     * description: 获取图片集合
     */
    public List<String> getImgPathList() {
        List<String> path_list = new ArrayList<>();
        List<EditData> editList = buildEditorData();
        for (ContentEditor.EditData itemData : editList) {
            if (itemData.imagePath != null) {
                path_list.add(itemData.imagePath);
            }
        }
        return path_list;
    }

    /**
     * author: sca_tl
     * description: 异步方式显示数据
     */
    public void setEditorData(final String content) {
        rootLayout.removeAllViews();
        Observable.create(new ObservableOnSubscribe<JSONObject>() {

            @Override
            public void subscribe(ObservableEmitter<JSONObject> emitter) {
                try {
                    JSONArray jsonArray = JSONObject.parseArray(content);
                    for (int i = 0; i < jsonArray.size(); i++) {
                        emitter.onNext(jsonArray.getJSONObject(i));
                    }
                    emitter.onComplete();
                } catch (Exception e) {
                    e.printStackTrace();
                    emitter.onError(e);
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<JSONObject>() {

            @Override
            public void onComplete() {
                if (rootLayout.getChildAt(0) instanceof EditText) {
                    EditText editText = (EditText) rootLayout.getChildAt(0);
                    if (TextUtils.isEmpty(editText.getText().toString())) {
                        rootLayout.removeView(editText);
                    }
                }
                // 在全部插入完毕后,再插入一个EditText,防止最后一张图片后无法插入文字
                if (rootLayout.getChildAt(getLastIndex()) instanceof RelativeLayout) {
                    addEditTextAtIndex(getLastIndex(), "");
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(JSONObject content_json) {
                try {
                    int type = content_json.getIntValue("content_type");
                    String content = content_json.getString("content");
                    if (type == CONTENT_TYPE_TEXT) {
                        addEditTextAtIndex(getLastIndex(), content);
                    }
                    if (type == CONTENT_TYPE_IMAGE) {
                        // addEditTextAtIndex(getLastIndex(), "");
                        addImageViewAtIndex(getLastIndex(), content);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public clreplaced EditData {

        // 文本内容
        public String inputStr;

        // 图片路径
        public String imagePath;

        // 0为文本,1为图片
        public int content_type;

        public Bitmap bitmap;
    }

    public interface OnRtImageDeleteListener {

        void onRtImageDelete(String imagePath);
    }

    public void setOnRtImageDeleteListener(OnRtImageDeleteListener onRtImageDeleteListener) {
        this.onRtImageDeleteListener = onRtImageDeleteListener;
    }

    public interface OnRtImageClickListener {

        void onRtImageClick(View view, String imagePath);
    }

    public void setOnRtImageClickListener(OnRtImageClickListener onRtImageClickListener) {
        this.onRtImageClickListener = onRtImageClickListener;
    }
}

18 Source : PropertyAnimationActivity.java
with Apache License 2.0
from RealMoMo

// LayoutAnimator--------------------------------------------------------------------------------
private void doLayoutAnimator() {
    LayoutTransition layoutTransition = new LayoutTransition();
    layoutTransition.setAnimator(LayoutTransition.APPEARING, getObjectAnimator(false));
    layoutTransition.setAnimator(LayoutTransition.DISAPPEARING, getObjectAnimator(true));
    layoutTransition.setDuration(2000);
    // mPuppet's parentView
    ViewGroup contentView = (ViewGroup) ((ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content)).getChildAt(0);
    contentView.setLayoutTransition(layoutTransition);
    if (contentView.findViewById(R.id.view_puppet) == null) {
        contentView.addView(mPuppet);
    } else {
        contentView.removeView(mPuppet);
    }
}

18 Source : UserFragment.java
with GNU Affero General Public License v3.0
from qwsem

private void initAnim() {
    mInAnim = ObjectAnimator.ofPropertyValuesHolder(this, PropertyValuesHolder.ofFloat("alpha", 0f, 1f), PropertyValuesHolder.ofFloat("translationX", 100f, 0f));
    mOutAnim = ObjectAnimator.ofPropertyValuesHolder(this, PropertyValuesHolder.ofFloat("alpha", 1f, 0f), PropertyValuesHolder.ofFloat("translationX", 0f, 100f));
    LayoutTransition mTransition = new LayoutTransition();
    mTransition.setDuration(LayoutTransition.CHANGE_APPEARING, 100);
    mTransition.setDuration(LayoutTransition.CHANGE_DISAPPEARING, 200);
    mTransition.setDuration(LayoutTransition.APPEARING, 200);
    mTransition.setDuration(LayoutTransition.DISAPPEARING, 100);
    // -----------------------设置动画--------------------
    mTransition.setAnimator(LayoutTransition.APPEARING, mInAnim);
    mTransition.setAnimator(LayoutTransition.DISAPPEARING, mOutAnim);
    // ---------------------------------------------------
    mTransition.setStartDelay(LayoutTransition.CHANGE_APPEARING, 0);
    mTransition.setStartDelay(LayoutTransition.APPEARING, 0);
    mTransition.setStartDelay(LayoutTransition.DISAPPEARING, 0);
    mTransition.setStartDelay(LayoutTransition.CHANGE_DISAPPEARING, 50);
    // ----viewgroup绑定----
    mOtherGroup.setLayoutTransition(mTransition);
}

18 Source : BaseWindowActivity.java
with Apache License 2.0
from nhirokinet

protected void enableWindowAnimationForEachViewGroup(ViewGroup viewGroup) {
    LayoutTransition lt = viewGroup.getLayoutTransition();
    lt.enableTransitionType(LayoutTransition.CHANGING);
    viewGroup.setLayoutTransition(lt);
}

18 Source : BaseWindowActivity.java
with Apache License 2.0
from nhirokinet

protected void disableWindowAnimationForEachViewGroup(ViewGroup viewGroup) {
    LayoutTransition lt = viewGroup.getLayoutTransition();
    lt.disableTransitionType(LayoutTransition.CHANGING);
    viewGroup.setLayoutTransition(lt);
}

18 Source : WeatherChartView.java
with Apache License 2.0
from li-yu

/**
 * Created by liyu on 2016/12/8.
 */
public clreplaced WeatherChartView extends LinearLayout {

    private boolean canRefresh = true;

    private List<FakeWeather.FakeForecastDaily> dailyForecastList = new ArrayList<>();

    LinearLayout.LayoutParams cellParams;

    LinearLayout.LayoutParams rowParams;

    LinearLayout.LayoutParams chartParams;

    LayoutTransition transition = new LayoutTransition();

    public WeatherChartView(Context context) {
        this(context, null);
    }

    public WeatherChartView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WeatherChartView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.setOrientation(VERTICAL);
        transition.enableTransitionType(LayoutTransition.APPEARING);
        this.setLayoutTransition(transition);
        rowParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        cellParams = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1);
        chartParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    }

    private void lereplacedGo() {
        removeAllViews();
        final LinearLayout datereplacedleView = new LinearLayout(getContext());
        datereplacedleView.setLayoutParams(rowParams);
        datereplacedleView.setOrientation(HORIZONTAL);
        datereplacedleView.setLayoutTransition(transition);
        datereplacedleView.removeAllViews();
        final LinearLayout iconView = new LinearLayout(getContext());
        iconView.setLayoutParams(rowParams);
        iconView.setOrientation(HORIZONTAL);
        iconView.setLayoutTransition(transition);
        iconView.removeAllViews();
        final LinearLayout weatherStrView = new LinearLayout(getContext());
        weatherStrView.setLayoutParams(rowParams);
        weatherStrView.setOrientation(HORIZONTAL);
        weatherStrView.setLayoutTransition(transition);
        weatherStrView.removeAllViews();
        List<Integer> minTemp = new ArrayList<>();
        List<Integer> maxTemp = new ArrayList<>();
        for (int i = 0; i < dailyForecastList.size(); i++) {
            final TextView tvDate = new TextView(getContext());
            tvDate.setGravity(Gravity.CENTER);
            tvDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
            tvDate.setTextColor(getResources().getColor(R.color.colorTextDark));
            tvDate.setVisibility(INVISIBLE);
            final TextView tvWeather = new TextView((getContext()));
            tvWeather.setGravity(Gravity.CENTER);
            tvWeather.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
            tvWeather.setTextColor(getResources().getColor(R.color.colorTextDark));
            tvWeather.setVisibility(INVISIBLE);
            final ImageView ivIcon = new ImageView(getContext());
            ivIcon.setAdjustViewBounds(true);
            ivIcon.setScaleType(ImageView.ScaleType.FIT_CENTER);
            int padding = SizeUtils.dp2px(getContext(), 10);
            int width = SizeUtils.getScreenWidth(getContext()) / dailyForecastList.size();
            LayoutParams ivParam = new LayoutParams(width, width);
            ivParam.weight = 1;
            ivIcon.setLayoutParams(ivParam);
            ivIcon.setPadding(padding, padding, padding, padding);
            ivIcon.setVisibility(INVISIBLE);
            tvDate.setText(dailyForecastList.get(i).getDate());
            tvWeather.setText(dailyForecastList.get(i).getTxt());
            WeatherUtil.getInstance().getWeatherDict(dailyForecastList.get(i).getCode()).observeOn(AndroidSchedulers.mainThread()).subscribe(new SimpleSubscriber<WeatherBean>() {

                @Override
                public void onNext(WeatherBean weatherBean) {
                    Glide.with(getContext()).load(weatherBean.getIcon()).diskCacheStrategy(DiskCacheStrategy.ALL).into(ivIcon);
                }
            });
            minTemp.add(Integer.valueOf(dailyForecastList.get(i).getMinTemp()));
            maxTemp.add(Integer.valueOf(dailyForecastList.get(i).getMaxTemp()));
            weatherStrView.addView(tvWeather, cellParams);
            datereplacedleView.addView(tvDate, cellParams);
            iconView.addView(ivIcon);
            this.postDelayed(new Runnable() {

                @Override
                public void run() {
                    tvDate.setVisibility(VISIBLE);
                    tvWeather.setVisibility(VISIBLE);
                    ivIcon.setVisibility(VISIBLE);
                }
            }, 200 * i);
        }
        addView(datereplacedleView);
        addView(iconView);
        addView(weatherStrView);
        final ChartView chartView = new ChartView(getContext());
        chartView.setData(minTemp, maxTemp);
        chartView.setPadding(0, SizeUtils.dp2px(getContext(), 16), 0, SizeUtils.dp2px(getContext(), 16));
        addView(chartView, chartParams);
    }

    public void setWeather(IFakeWeather weather) {
        if (weather == null || !canRefresh) {
            return;
        }
        dailyForecastList.clear();
        dailyForecastList.addAll(weather.getFakeForecastDaily());
        lereplacedGo();
        canRefresh = false;
        this.postDelayed(new Runnable() {

            @Override
            public void run() {
                canRefresh = true;
            }
        }, weather.getFakeForecastDaily().size() * 200);
    }
}

18 Source : ViewGroupUtilsApi14.java
with Apache License 2.0
from covidsafewatch

private static void cancelLayoutTransition(LayoutTransition layoutTransition) {
    if (!sCancelMethodFetched) {
        try {
            Method declaredMethod = LayoutTransition.clreplaced.getDeclaredMethod("cancel", new Clreplaced[0]);
            sCancelMethod = declaredMethod;
            declaredMethod.setAccessible(true);
        } catch (NoSuchMethodException unused) {
            Log.i(TAG, "Failed to access cancel method by reflection");
        }
        sCancelMethodFetched = true;
    }
    Method method = sCancelMethod;
    if (method != null) {
        try {
            method.invoke(layoutTransition, new Object[0]);
        } catch (IllegalAccessException unused2) {
            Log.i(TAG, "Failed to access cancel method by reflection");
        } catch (InvocationTargetException unused3) {
            Log.i(TAG, "Failed to invoke cancel method by reflection");
        }
    }
}

17 Source : HyperTextEditor.java
with Apache License 2.0
from yangchong211

/**
 * <pre>
 *     @author 杨充
 *     blog  : https://github.com/yangchong211
 *     time  : 2016/3/31
 *     desc  : 编辑富文本
 *     revise:
 * </pre>
 */
public clreplaced HyperTextEditor extends ScrollView {

    /**
     * editText常规padding是10dp
     */
    private static final int EDIT_PADDING = 10;

    /**
     * 新生的view都会打一个tag,对每个view来说,这个tag是唯一的。
     */
    private int viewTagIndex = 1;

    /**
     * 这个是所有子view的容器,scrollView内部的唯一一个ViewGroup
     */
    private LinearLayout layout;

    /**
     * inflater对象
     */
    private LayoutInflater inflater;

    /**
     * 所有EditText的软键盘监听器
     */
    private OnKeyListener keyListener;

    /**
     * 图片右上角红叉按钮监听器
     */
    private OnClickListener btnListener;

    /**
     * 所有EditText的焦点监听listener
     */
    private OnFocusChangeListener focusListener;

    /**
     * 所有EditText的文本变化监听listener
     */
    private Texreplacedcher texreplacedcher;

    /**
     * 最近被聚焦的EditText
     */
    private EditText lastFocusEdit;

    /**
     * 只在图片View添加或remove时,触发transition动画
     */
    private LayoutTransition mTransition;

    private int editNormalPadding = 0;

    /**
     * 删除该图片,消失的图片控件索引
     */
    private int disappearingImageIndex = 0;

    /**
     * 图片地址集合
     */
    private ArrayList<String> imagePaths;

    /**
     * 关键词高亮
     */
    private String keywords;

    /**
     * 插入的图片显示高度
     */
    private int rtImageHeight;

    /**
     * 父控件的上和下padding
     */
    private int topAndBottom;

    /**
     * 父控件的左和右padding
     */
    private int leftAndRight;

    /**
     * 两张相邻图片间距
     */
    private int rtImageBottom = 10;

    /**
     * 文字相关属性,初始提示信息,文字大小和颜色
     */
    private String rtTextInitHint = "请输入内容";

    /**
     * 文字大小
     */
    private int rtTextSize = 16;

    /**
     * 文字颜色
     */
    private int rtTextColor = Color.parseColor("#757575");

    private int rtHintTextColor = Color.parseColor("#B0B1B8");

    /**
     * 文字行间距
     */
    private int rtTextLineSpace = 8;

    /**
     * 富文本的文字长度
     */
    private int contentLength = 0;

    /**
     * 富文本的图片个数
     */
    private int imageLength = 0;

    /**
     * 删除图片的位置
     */
    private int delIconLocation = 0;

    /**
     * 自定义输入文本的光标颜色
     */
    private int cursorColor;

    private OnHyperEditListener onHyperListener;

    private OnHyperChangeListener onHyperChangeListener;

    /**
     * 保存重要信息
     * @return
     */
    @Nullable
    @Override
    protected Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        TextEditorState viewState = new TextEditorState(superState);
        viewState.rtImageHeight = rtImageHeight;
        return viewState;
    }

    /**
     * 复现
     * @param state								state
     */
    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        TextEditorState viewState = (TextEditorState) state;
        rtImageHeight = viewState.rtImageHeight;
        super.onRestoreInstanceState(viewState.getSuperState());
        requestLayout();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mTransition != null) {
            // 移除Layout变化监听
            mTransition.removeTransitionListener(transitionListener);
            HyperLogUtils.d("HyperTextEditor----onDetachedFromWindow------移除Layout变化监听");
        }
    }

    public HyperTextEditor(Context context) {
        this(context, null);
    }

    public HyperTextEditor(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HyperTextEditor(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        imagePaths = new ArrayList<>();
        inflater = LayoutInflater.from(context);
        initAttrs(context, attrs);
        initLayoutView(context);
        initListener();
        initFirstEditText(context);
    }

    private void initLayoutView(Context context) {
        // 初始化layout
        layout = new LinearLayout(context);
        layout.setOrientation(LinearLayout.VERTICAL);
        // 禁止载入动画
        setUpLayoutTransitions();
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        // 设置间距,防止生成图片时文字太靠边,不能用margin,否则有黑边
        layout.setPadding(leftAndRight, topAndBottom, leftAndRight, topAndBottom);
        addView(layout, layoutParams);
    }

    /**
     * 初始化自定义属性
     * @param context						context上下文
     * @param attrs							attrs属性
     */
    private void initAttrs(Context context, AttributeSet attrs) {
        // 获取自定义属性
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.HyperTextEditor);
        topAndBottom = ta.getDimensionPixelSize(R.styleable.HyperTextEditor_editor_layout_top_bottom, 15);
        leftAndRight = ta.getDimensionPixelSize(R.styleable.HyperTextEditor_editor_layout_right_left, 40);
        rtImageHeight = ta.getDimensionPixelSize(R.styleable.HyperTextEditor_editor_image_height, 250);
        rtImageBottom = ta.getDimensionPixelSize(R.styleable.HyperTextEditor_editor_image_bottom, 10);
        rtTextSize = ta.getDimensionPixelSize(R.styleable.HyperTextEditor_editor_text_size, 16);
        rtTextLineSpace = ta.getDimensionPixelSize(R.styleable.HyperTextEditor_editor_text_line_space, 8);
        rtTextColor = ta.getColor(R.styleable.HyperTextEditor_editor_text_color, Color.parseColor("#757575"));
        rtHintTextColor = ta.getColor(R.styleable.HyperTextEditor_editor_hint_text_color, Color.parseColor("#B0B1B8"));
        rtTextInitHint = ta.getString(R.styleable.HyperTextEditor_editor_text_init_hint);
        delIconLocation = ta.getInt(R.styleable.HyperTextEditor_editor_del_icon_location, 0);
        cursorColor = ta.getColor(R.styleable.HyperTextEditor_editor_text_cursor_color, Color.parseColor("#FF434F"));
        ta.recycle();
    }

    private void initListener() {
        // 初始化键盘退格监听,主要用来处理点击回删按钮时,view的一些列合并操作
        keyListener = new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // KeyEvent.KEYCODE_DEL    删除插入点之前的字符
                if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
                    EditText edit = (EditText) v;
                    // 处于退格删除的逻辑
                    onBackspacePress(edit);
                }
                return false;
            }
        };
        // 图片删除图标叉掉处理
        btnListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (v instanceof HyperImageView) {
                    HyperImageView imageView = (HyperImageView) v;
                    // 开放图片点击接口
                    if (onHyperListener != null) {
                        onHyperListener.onImageClick(imageView, imageView.getAbsolutePath());
                    }
                } else if (v instanceof ImageView) {
                    FrameLayout parentView = (FrameLayout) v.getParent();
                    // 图片删除图片点击事件
                    if (onHyperListener != null) {
                        onHyperListener.onImageCloseClick(parentView);
                    }
                // onImageCloseClick(parentView);
                }
            }
        };
        focusListener = new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    lastFocusEdit = (EditText) v;
                    HyperLogUtils.d("HyperTextEditor---onFocusChange--" + lastFocusEdit);
                }
            }
        };
        texreplacedcher = new Texreplacedcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                addHyperEditorChangeListener();
                HyperLogUtils.d("HyperTextEditor---onTextChanged--文字--" + contentLength + "--图片-" + imageLength);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        };
    }

    private void initFirstEditText(Context context) {
        LinearLayout.LayoutParams firstEditParam = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        int padding = HyperLibUtils.dip2px(context, EDIT_PADDING);
        EditText firstEdit = createEditText(rtTextInitHint, padding);
        layout.addView(firstEdit, firstEditParam);
        lastFocusEdit = firstEdit;
    }

    /**
     * 处理软键盘backSpace回退事件
     * @param editText 					光标所在的文本输入框
     */
    @SuppressLint("SetTextI18n")
    private void onBackspacePress(EditText editText) {
        if (editText == null) {
            return;
        }
        try {
            int startSelection = editText.getSelectionStart();
            // 只有在光标已经顶到文本输入框的最前方,在判定是否删除之前的图片,或两个View合并
            if (startSelection == 0) {
                // 获取当前控件在layout父容器中的索引
                int editIndex = layout.indexOfChild(editText);
                // 如果editIndex-1<0,
                View preView = layout.getChildAt(editIndex - 1);
                if (null != preView) {
                    if (preView instanceof FrameLayout) {
                        // 光标EditText的上一个view对应的是图片,删除图片操作
                        onImageCloseClick(preView);
                    } else if (preView instanceof EditText) {
                        // 光标EditText的上一个view对应的还是文本框EditText,删除文字操作
                        String str1 = editText.getText().toString();
                        EditText preEdit = (EditText) preView;
                        String str2 = preEdit.getText().toString();
                        // 合并文本view时,不需要transition动画
                        layout.setLayoutTransition(null);
                        // 移除editText文本控件
                        layout.removeView(editText);
                        // 恢复transition动画
                        layout.setLayoutTransition(mTransition);
                        // 文本合并操作
                        preEdit.setText(str2 + str1);
                        preEdit.requestFocus();
                        preEdit.setSelection(str2.length(), str2.length());
                        lastFocusEdit = preEdit;
                    }
                } else {
                    HyperLogUtils.d("HyperTextEditor----onBackspacePress------没有上一个view");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理图片上删除的点击事件
     * 删除类型 0代表backspace删除 1代表按红叉按钮删除
     * @param view 							整个image对应的relativeLayout view
     */
    public void onImageCloseClick(View view) {
        try {
            // 判断过渡动画是否结束,只能等到结束才可以操作
            if (!mTransition.isRunning()) {
                // 获取当前要删除图片控件的索引值
                disappearingImageIndex = layout.indexOfChild(view);
                // 删除文件夹里的图片
                List<HyperEditData> dataList = buildEditData();
                // 获取要删除图片控件的数据
                HyperEditData editData = dataList.get(disappearingImageIndex);
                if (editData.getImagePath() != null) {
                    if (onHyperListener != null) {
                        onHyperListener.onRtImageDelete(editData.getImagePath());
                    }
                    // SDCardUtil.deleteFile(editData.imagePath);
                    // 从图片集合中移除图片链接
                    imagePaths.remove(editData.getImagePath());
                    addHyperEditorChangeListener();
                }
                // 然后移除当前view
                layout.removeView(view);
                // 合并上下EditText内容
                mergeEditText();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听富文本:文字+图片数量变化
     * 分别在图片插入,图片删除,以及文本变化时添加监听事件
     */
    private void addHyperEditorChangeListener() {
        getContentAndImageCount();
        int contentLength = getContentLength();
        int imageLength = getImageLength();
        if (onHyperChangeListener != null) {
            onHyperChangeListener.onImageClick(contentLength, imageLength);
        }
    }

    /**
     * 清空所有布局
     */
    public void clearAllLayout() {
        if (layout != null) {
            layout.removeAllViews();
        }
    }

    /**
     * 获取索引位置
     */
    public int getLastIndex() {
        if (layout != null) {
            int childCount = layout.getChildCount();
            return childCount;
        }
        return -1;
    }

    /**
     * 添加生成文本输入框
     * @param hint								内容
     * @param paddingTop						到顶部高度
     * @return
     */
    private EditText createEditText(String hint, int paddingTop) {
        EditText editText = new DeletableEditText(getContext());
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        editText.setLayoutParams(layoutParams);
        editText.setTextSize(16);
        editText.setTextColor(Color.parseColor("#616161"));
        editText.setCursorVisible(true);
        editText.setBackground(null);
        editText.setOnKeyListener(keyListener);
        editText.setOnFocusChangeListener(focusListener);
        editText.addTextChangedListener(texreplacedcher);
        editText.setTag(viewTagIndex++);
        editText.setPadding(editNormalPadding, paddingTop, editNormalPadding, paddingTop);
        editText.setHint(hint);
        editText.setTextSize(TypedValue.COMPLEX_UNIT_PX, rtTextSize);
        editText.setTextColor(rtTextColor);
        editText.setHintTextColor(rtHintTextColor);
        editText.setLineSpacing(rtTextLineSpace, 1.0f);
        HyperLibUtils.setCursorDrawableColor(editText, cursorColor);
        return editText;
    }

    /**
     * 生成图片View
     */
    private FrameLayout createImageLayout() {
        FrameLayout layout = (FrameLayout) inflater.inflate(R.layout.hte_edit_imageview, null);
        layout.setTag(viewTagIndex++);
        ImageView closeView = layout.findViewById(R.id.image_close);
        FrameLayout.LayoutParams layoutParams = (LayoutParams) closeView.getLayoutParams();
        layoutParams.bottomMargin = HyperLibUtils.dip2px(layout.getContext(), 10.0f);
        switch(delIconLocation) {
            // 左上角
            case 1:
                layoutParams.gravity = Gravity.TOP | Gravity.START;
                closeView.setLayoutParams(layoutParams);
                break;
            // 右上角
            case 2:
                layoutParams.gravity = Gravity.TOP | Gravity.END;
                closeView.setLayoutParams(layoutParams);
                break;
            // 左下角
            case 3:
                layoutParams.gravity = Gravity.BOTTOM | Gravity.START;
                closeView.setLayoutParams(layoutParams);
                break;
            // 右下角
            case 4:
                layoutParams.gravity = Gravity.BOTTOM | Gravity.END;
                closeView.setLayoutParams(layoutParams);
                break;
            // 其他右下角
            default:
                layoutParams.gravity = Gravity.BOTTOM | Gravity.END;
                closeView.setLayoutParams(layoutParams);
                break;
        }
        closeView.setTag(layout.getTag());
        closeView.setOnClickListener(btnListener);
        HyperImageView imageView = layout.findViewById(R.id.edit_imageView);
        imageView.setOnClickListener(btnListener);
        return layout;
    }

    /**
     * 插入一张图片
     * @param imagePath							图片路径地址
     */
    public synchronized void insertImage(String imagePath) {
        // bitmap == null时,可能是网络图片,不能做限制
        if (TextUtils.isEmpty(imagePath)) {
            return;
        }
        try {
            // lastFocusEdit获取焦点的EditText
            String lastEditStr = lastFocusEdit.getText().toString();
            // 获取光标所在位置
            int cursorIndex = lastFocusEdit.getSelectionStart();
            // 获取光标前面的字符串
            String editStr1 = lastEditStr.substring(0, cursorIndex).trim();
            // 获取光标后的字符串
            String editStr2 = lastEditStr.substring(cursorIndex).trim();
            // 获取焦点的EditText所在位置
            int lastEditIndex = layout.indexOfChild(lastFocusEdit);
            if (lastEditStr.length() == 0) {
                // 如果当前获取焦点的EditText为空,直接在EditText下方插入图片,并且插入空的EditText
                addEditTextAtIndex(lastEditIndex + 1, "");
                addImageViewAtIndex(lastEditIndex + 1, imagePath);
            } else if (editStr1.length() == 0) {
                // 如果光标已经顶在了editText的最前面,则直接插入图片,并且EditText下移即可
                addImageViewAtIndex(lastEditIndex, imagePath);
                // 同时插入一个空的EditText,防止插入多张图片无法写文字
                addEditTextAtIndex(lastEditIndex + 1, "");
            } else if (editStr2.length() == 0) {
                // 如果光标已经顶在了editText的最末端,则需要添加新的imageView和EditText
                addEditTextAtIndex(lastEditIndex + 1, "");
                addImageViewAtIndex(lastEditIndex + 1, imagePath);
            } else {
                // 如果光标已经顶在了editText的最中间,则需要分割字符串,分割成两个EditText,并在两个EditText中间插入图片
                // 把光标前面的字符串保留,设置给当前获得焦点的EditText(此为分割出来的第一个EditText)
                lastFocusEdit.setText(editStr1);
                // 把光标后面的字符串放在新创建的EditText中(此为分割出来的第二个EditText)
                addEditTextAtIndex(lastEditIndex + 1, editStr2);
                // 在第二个EditText的位置插入一个空的EditText,以便连续插入多张图片时,有空间写文字,第二个EditText下移
                addEditTextAtIndex(lastEditIndex + 1, "");
                // 在空的EditText的位置插入图片布局,空的EditText下移
                addImageViewAtIndex(lastEditIndex + 1, imagePath);
            }
            // 隐藏小键盘
            hideKeyBoard();
            // 监听富文本:文字+图片数量变化
            addHyperEditorChangeListener();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 隐藏小键盘
     */
    private void hideKeyBoard() {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null && lastFocusEdit != null) {
            imm.hideSoftInputFromWindow(lastFocusEdit.getWindowToken(), 0);
        }
    }

    public void setKeywords(String keywords) {
        this.keywords = keywords;
    }

    /**
     * 在特定位置插入EditText
     * @param index							位置
     * @param editStr						EditText显示的文字
     */
    public synchronized void addEditTextAtIndex(final int index, CharSequence editStr) {
        try {
            EditText editText = createEditText("插入文字", EDIT_PADDING);
            if (!TextUtils.isEmpty(keywords)) {
                // 搜索关键词高亮
                SpannableStringBuilder textStr = HyperLibUtils.highlight(editStr.toString(), keywords, Color.parseColor("#EE5C42"));
                editText.setText(textStr);
            } else if (!TextUtils.isEmpty(editStr)) {
                // 判断插入的字符串是否为空,如果没有内容则显示hint提示信息
                editText.setText(editStr);
            }
            // 请注意此处,EditText添加、或删除不触动Transition动画
            layout.setLayoutTransition(null);
            layout.addView(editText, index);
            // remove之后恢复transition动画
            layout.setLayoutTransition(mTransition);
            // 插入新的EditText之后,修改lastFocusEdit的指向
            lastFocusEdit = editText;
            // 获取焦点
            lastFocusEdit.requestFocus();
            // 将光标移至文字指定索引处
            lastFocusEdit.setSelection(editStr.length(), editStr.length());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 在特定位置添加ImageView
     */
    public synchronized void addImageViewAtIndex(final int index, final String imagePath) {
        if (TextUtils.isEmpty(imagePath)) {
            return;
        }
        try {
            imagePaths.add(imagePath);
            final FrameLayout imageLayout = createImageLayout();
            HyperImageView imageView = imageLayout.findViewById(R.id.edit_imageView);
            imageView.setAbsolutePath(imagePath);
            HyperManager.getInstance().loadImage(imagePath, imageView, rtImageHeight);
            layout.addView(imageLayout, index);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化transition动画
     */
    private void setUpLayoutTransitions() {
        mTransition = new LayoutTransition();
        // 添加Layout变化监听
        mTransition.addTransitionListener(transitionListener);
        // 若向ViewGroup中添加一个ImageView,ImageView对象可以设置动画(即APPEARING 动画形式),
        // ViewGroup中的其它ImageView对象此时移动到新的位置的过程中也可以设置相关的动画(即CHANGE_APPEARING 动画形式)。
        mTransition.enableTransitionType(LayoutTransition.APPEARING);
        // 设置整个Layout变换动画时间
        mTransition.setDuration(300);
        layout.setLayoutTransition(mTransition);
    }

    private LayoutTransition.TransitionListener transitionListener = new LayoutTransition.TransitionListener() {

        /**
         * LayoutTransition某一类型动画开始
         * @param transition				transition
         * @param container					container容器
         * @param view						view控件
         * @param transitionType			类型
         */
        @Override
        public void startTransition(LayoutTransition transition, ViewGroup container, View view, int transitionType) {
        }

        /**
         * LayoutTransition某一类型动画结束
         * @param transition				transition
         * @param container					container容器
         * @param view						view控件
         * @param transitionType			类型
         */
        @Override
        public void endTransition(LayoutTransition transition, ViewGroup container, View view, int transitionType) {
            if (!transition.isRunning() && transitionType == LayoutTransition.CHANGE_DISAPPEARING) {
                // transition动画结束,合并EditText
                mergeEditText();
            }
        }
    };

    /**
     * 图片删除的时候,如果上下方都是EditText,则合并处理
     */
    private void mergeEditText() {
        try {
            View preView = layout.getChildAt(disappearingImageIndex - 1);
            View nextView = layout.getChildAt(disappearingImageIndex);
            if (preView instanceof EditText && nextView instanceof EditText) {
                EditText preEdit = (EditText) preView;
                EditText nextEdit = (EditText) nextView;
                String str1 = preEdit.getText().toString();
                String str2 = nextEdit.getText().toString();
                String mergeText = "";
                if (str2.length() > 0) {
                    mergeText = str1 + "\n" + str2;
                } else {
                    mergeText = str1;
                }
                layout.setLayoutTransition(null);
                layout.removeView(nextEdit);
                preEdit.setText(mergeText);
                // 设置光标的定位
                preEdit.requestFocus();
                preEdit.setSelection(str1.length(), str1.length());
                // 设置动画
                layout.setLayoutTransition(mTransition);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 对外提供的接口, 生成编辑数据上传
     */
    public List<HyperEditData> buildEditData() {
        List<HyperEditData> dataList = new ArrayList<>();
        try {
            int num = layout.getChildCount();
            for (int index = 0; index < num; index++) {
                View itemView = layout.getChildAt(index);
                HyperEditData hyperEditData = new HyperEditData();
                if (itemView instanceof EditText) {
                    // 文本
                    EditText item = (EditText) itemView;
                    hyperEditData.setInputStr(item.getText().toString());
                    hyperEditData.setType(1);
                } else if (itemView instanceof FrameLayout) {
                    // 图片
                    HyperImageView item = itemView.findViewById(R.id.edit_imageView);
                    hyperEditData.setImagePath(item.getAbsolutePath());
                    hyperEditData.setType(2);
                }
                dataList.add(hyperEditData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        HyperLogUtils.d("HyperTextEditor----buildEditData------dataList---" + dataList.size());
        return dataList;
    }

    /**
     * 用于统计文本文字的数量和图片的数量
     */
    public void getContentAndImageCount() {
        contentLength = 0;
        imageLength = 0;
        if (layout == null) {
            return;
        }
        try {
            int num = layout.getChildCount();
            for (int index = 0; index < num; index++) {
                View itemView = layout.getChildAt(index);
                if (itemView instanceof EditText) {
                    // 文本
                    EditText item = (EditText) itemView;
                    if (item.getText() != null) {
                        String string = item.getText().toString().trim();
                        int length = string.length();
                        contentLength = contentLength + length;
                    }
                } else if (itemView instanceof FrameLayout) {
                    // 图片
                    imageLength++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        HyperLogUtils.d("HyperTextEditor----buildEditData------dataList---");
    }

    /**
     * 上传图片成功之后,替换本地图片路径
     * @param url						网络图片
     * @param localPath					本地图片
     */
    public void setImageUrl(String url, String localPath) {
        HyperLogUtils.d("HyperTextEditor----setImageUrl1------" + url + "----" + localPath);
        if (layout == null) {
            return;
        }
        try {
            int num = layout.getChildCount();
            for (int index = 0; index < num; index++) {
                View itemView = layout.getChildAt(index);
                if (itemView instanceof FrameLayout) {
                    // 图片控件,需要替换图片url
                    HyperImageView item = itemView.findViewById(R.id.edit_imageView);
                    if (item.getAbsolutePath().equals(localPath)) {
                        item.setAbsolutePath(url);
                        HyperLogUtils.d("HyperTextEditor----setImageUrl2------" + url + "----" + localPath);
                        return;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setOnHyperListener(OnHyperEditListener listener) {
        this.onHyperListener = listener;
    }

    public void setOnHyperChangeListener(OnHyperChangeListener onHyperChangeListener) {
        this.onHyperChangeListener = onHyperChangeListener;
    }

    public EditText getLastFocusEdit() {
        return lastFocusEdit;
    }

    public int getContentLength() {
        return contentLength;
    }

    public int getImageLength() {
        return imageLength;
    }

    /**
     * 修改加粗样式
     */
    public void bold() {
        SpanTextHelper.getInstance().bold(lastFocusEdit);
    }

    /**
     * 修改斜体样式
     */
    public void italic() {
        SpanTextHelper.getInstance().italic(lastFocusEdit);
    }

    /**
     * 修改加粗斜体样式
     */
    public void boldItalic() {
        SpanTextHelper.getInstance().boldItalic(lastFocusEdit);
    }

    /**
     * 修改删除线样式
     */
    public void strikeThrough() {
        SpanTextHelper.getInstance().strikeThrough(lastFocusEdit);
    }

    /**
     * 修改下划线样式
     */
    public void underline() {
        SpanTextHelper.getInstance().underline(lastFocusEdit);
    }
}

17 Source : SubredditActivity.java
with Apache License 2.0
from saket

@Override
protected void onPostCreate(@Nullable Bundle savedState) {
    super.onPostCreate(savedState);
    setupController();
    setupSubmissionRecyclerView(savedState);
    loadSubmissions(savedState == null);
    setupSubmissionPage();
    setupToolbarSheet();
    // Restore state of subreddit picker sheet / user profile sheet.
    if (savedState != null) {
        if (savedState.getBoolean(KEY_IS_SUBREDDIT_PICKER_SHEET_VISIBLE)) {
            showSubredditPickerSheet(false);
        } else if (savedState.getBoolean(KEY_IS_USER_PROFILE_SHEET_VISIBLE)) {
            showUserProfileSheet();
        }
    }
    if (getIntent().hasExtra(KEY_SUBREDDIT_LINK)) {
        RedditSubredditLink initialSubreddit = getIntent().getParcelableExtra(KEY_SUBREDDIT_LINK);
        subredditChangesStream.accept(initialSubreddit.name());
    }
    // Animate changes in sorting button's width on text change.
    LayoutTransition layoutTransition = sortingModeContainer.getLayoutTransition();
    layoutTransition.enableTransitionType(LayoutTransition.CHANGING);
    if (savedState != null && savedState.containsKey(KEY_SORTING_AND_TIME_PERIOD)) {
        // noinspection ConstantConditions
        sortingChangesStream.accept(savedState.getParcelable(KEY_SORTING_AND_TIME_PERIOD));
    } else {
        sortingChangesStream.accept(new SortingAndTimePeriod(Reddit.Companion.DEFAULT_SUBREDDIT_SORT()));
    }
    sortingChangesStream.takeUntil(lifecycle().onDestroy()).subscribe(sortingAndTimePeriod -> {
        if (sortingAndTimePeriod.sortOrder().getRequiresTimePeriod()) {
            sortingModeButton.setText(getString(R.string.subreddit_sorting_mode_with_time_period, getString(sortingAndTimePeriod.sortingDisplayTextRes()), getString(sortingAndTimePeriod.timePeriodDisplayTextRes())));
        } else {
            sortingModeButton.setText(getString(R.string.subreddit_sorting_mode, getString(sortingAndTimePeriod.sortingDisplayTextRes())));
        }
    });
    // Subscribe button.
    subredditChangesStream.switchMap(subredditName -> subscriptionRepository.isSubscribed(subredditName).subscribeOn(io()).observeOn(mainThread()).map(isSubscribed -> isSubscribed ? View.GONE : View.VISIBLE)).startWith(View.GONE).doOnError(e -> Timber.e(e, "Couldn't get subscribed status for %s", subredditChangesStream.getValue())).onErrorResumeNext(Observable.just(View.GONE)).takeUntil(lifecycle().onDestroy()).subscribe(subscribeVisibility -> subscribeButton.setVisibility(subscribeVisibility));
    userSessionRepository.get().streamSessions().skip(1).takeUntil(lifecycle().onDestroy()).subscribe(session -> {
        if (session.isPresent()) {
            handleOnUserLogIn();
        } else {
            handleOnUserLogOut();
        }
    });
}

17 Source : SearchActivity.java
with MIT License
from paizhangpi

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    // If SearchActivity Usage is set to not be saved
    if (!(PrefsHelper.getBooleanPrefs("isSaveSearchUsage", this))) {
        PrefsHelper.clearPrefs("searchFiltersSpinner", this);
        PrefsHelper.clearPrefs("searchOptionsSpinner", this);
    }
    // If EveryMac enabled, a message should append.
    if (PrefsHelper.getBooleanPrefs("isOpenEveryMac", this)) {
        this.setreplacedle(getString(R.string.menu_search) + getString(R.string.menu_group_everymac));
    } else {
        this.setreplacedle(R.string.menu_search);
    }
    final LinearLayout mainLayout = findViewById(R.id.mainLayout);
    LayoutTransition layoutTransition = mainLayout.getLayoutTransition();
    layoutTransition.enableTransitionType(LayoutTransition.CHANGING);
    filtersSpinner = findViewById(R.id.filtersSpinner);
    optionsSpinner = findViewById(R.id.optionsSpinner);
    initSpinners();
    initSearch();
    Log.i("SearchActivity", "Current Query: " + searchText.getQuery() + ", Current Manufacturer: " + translateFiltersParam() + ", Current Option: " + translateOptionsParam());
}

17 Source : ListActivity.java
with Apache License 2.0
from oldergod

private void setupTransitionDelay(ConstraintLayout activityList) {
    LayoutTransition layoutTransition = activityList.getLayoutTransition();
    layoutTransition.setDuration(200);
    layoutTransition.setAnimator(LayoutTransition.DISAPPEARING, null);
}

17 Source : LoadingDialogHeaderView.java
with MIT License
from crazyhitty

private void initializeViews(Context context) {
    LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    layoutInflater.inflate(R.layout.view_loading_dialog_header, this);
    // bind views
    ButterKnife.bind(this);
    // set layout params
    LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    setLayoutParams(layoutParams);
    LayoutTransition layoutTransition = new LayoutTransition();
    setLayoutTransition(layoutTransition);
}

17 Source : ViewGroupUtilsApi14.java
with Apache License 2.0
from androidx

/**
 * Note, this is only called on API 17 and older.
 */
@SuppressLint("SoonBlockedPrivateApi")
private static void cancelLayoutTransition(LayoutTransition t) {
    if (!sCancelMethodFetched) {
        try {
            sCancelMethod = LayoutTransition.clreplaced.getDeclaredMethod("cancel");
            sCancelMethod.setAccessible(true);
        } catch (NoSuchMethodException e) {
            Log.i(TAG, "Failed to access cancel method by reflection");
        }
        sCancelMethodFetched = true;
    }
    if (sCancelMethod != null) {
        try {
            sCancelMethod.invoke(t);
        } catch (IllegalAccessException e) {
            Log.i(TAG, "Failed to access cancel method by reflection");
        } catch (InvocationTargetException e) {
            Log.i(TAG, "Failed to invoke cancel method by reflection");
        }
    }
}

17 Source : IndicatorDots.java
with MIT License
from amirarcane

private void initView(Context context) {
    if (mIndicatorType == 0) {
        for (int i = 0; i < mPinLength; i++) {
            View dot = new View(context);
            emptyDot(dot);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mDotDiameter, mDotDiameter);
            params.setMargins(mDotSpacing, 0, mDotSpacing, 0);
            dot.setLayoutParams(params);
            addView(dot);
        }
    } else if (mIndicatorType == 2) {
        LayoutTransition layoutTransition = new LayoutTransition();
        layoutTransition.setDuration(DEFAULT_ANIMATION_DURATION);
        layoutTransition.setStartDelay(layoutTransition.APPEARING, 0);
        setLayoutTransition(layoutTransition);
    }
}

16 Source : PLiveCodingFeedback.java
with GNU General Public License v3.0
from victordiaz

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public View add() {
    // live execution layout
    liveRLayout = new LinearLayout(mContext);
    RelativeLayout.LayoutParams liveLayoutParams = new RelativeLayout.LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.MATCH_PARENT);
    liveLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    liveLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    liveRLayout.setLayoutParams(liveLayoutParams);
    liveRLayout.setGravity(Gravity.BOTTOM);
    liveRLayout.setBackgroundColor(bgColor);
    liveRLayout.setPadding(10, 10, 10, 10);
    liveRLayout.setVisibility(View.GONE);
    // liveRLayout.setLayoutTransition(transition)
    // Animation spinin = AnimationUtils.loadAnimation(this,
    // R.anim.slide_in_left);
    // liveRLayout.setLayoutAnimation(new
    // LayoutAnimationController(spinin));
    Animator appearingAnimation = ObjectAnimator.ofFloat(null, "translationY", 20, 0);
    appearingAnimation.addListener(new AnimatorListenerAdapter() {

        @Override
        public void onAnimationEnd(Animator anim) {
            View view = (View) ((ObjectAnimator) anim).getTarget();
            view.setTranslationX(0f);
        }
    });
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
        LayoutTransition l = new LayoutTransition();
        l.enableTransitionType(LayoutTransition.CHANGING);
        AnimatorSet as = (AnimatorSet) AnimatorInflater.loadAnimator(mContext, R.animator.live_code);
        // as.se
        l.setAnimator(LayoutTransition.APPEARING, as);
        l.setDuration(LayoutTransition.APPEARING, 300);
        l.setStartDelay(LayoutTransition.APPEARING, 0);
        liveRLayout.setLayoutTransition(l);
    }
    return liveRLayout;
}

16 Source : MyIDFragment.java
with GNU Affero General Public License v3.0
from threema-ch

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    if (!this.requiredInstances()) {
        logger.error("could not instantiate required objects");
        return null;
    }
    fragmentView = getView();
    if (fragmentView == null) {
        fragmentView = inflater.inflate(R.layout.fragment_my_id, container, false);
        this.updatePendingState(fragmentView, true);
        LayoutTransition l = new LayoutTransition();
        l.enableTransitionType(LayoutTransition.CHANGING);
        ViewGroup viewGroup = fragmentView.findViewById(R.id.fragment_id_container);
        viewGroup.setLayoutTransition(l);
        if (ConfigUtils.isWorkRestricted()) {
            Boolean value = AppRestrictionUtil.getBooleanRestriction(getString(R.string.restriction__readonly_profile));
            if (value != null) {
                isReadonlyProfile = value;
            }
            value = AppRestrictionUtil.getBooleanRestriction(getString(R.string.restriction__disable_send_profile_picture));
            if (value != null) {
                isDisabledProfilePicReleaseSettings = value;
            }
        }
        TextView textView = fragmentView.findViewById(R.id.keyfingerprint);
        textView.setText(fingerPrintService.getFingerPrint(getIdenreplacedy()));
        fragmentView.findViewById(R.id.policy_explain).setVisibility(isReadonlyProfile || AppRestrictionUtil.isBackupsDisabled(ThreemaApplication.getAppContext()) || AppRestrictionUtil.isIdBackupsDisabled(ThreemaApplication.getAppContext()) ? View.VISIBLE : View.GONE);
        final ImageView picReleaseConfImageView = fragmentView.findViewById(R.id.picrelease_config);
        picReleaseConfImageView.setOnClickListener(this);
        picReleaseConfImageView.setVisibility(preferenceService.getProfilePicRelease() == PreferenceService.PROFILEPIC_RELEASE_SOME ? View.VISIBLE : View.GONE);
        configureEditWithButton(fragmentView.findViewById(R.id.linked_email_layout), fragmentView.findViewById(R.id.change_email), isReadonlyProfile);
        configureEditWithButton(fragmentView.findViewById(R.id.linked_mobile_layout), fragmentView.findViewById(R.id.change_mobile), isReadonlyProfile);
        configureEditWithButton(fragmentView.findViewById(R.id.delete_id_layout), fragmentView.findViewById(R.id.delete_id), isReadonlyProfile);
        configureEditWithButton(fragmentView.findViewById(R.id.revocation_key_layout), fragmentView.findViewById(R.id.revocation_key), isReadonlyProfile);
        configureEditWithButton(fragmentView.findViewById(R.id.export_id_layout), fragmentView.findViewById(R.id.export_id), (AppRestrictionUtil.isBackupsDisabled(ThreemaApplication.getAppContext()) || AppRestrictionUtil.isIdBackupsDisabled(ThreemaApplication.getAppContext())));
        if (userService != null && userService.getIdenreplacedy() != null) {
            ((TextView) fragmentView.findViewById(R.id.my_id)).setText(userService.getIdenreplacedy());
            fragmentView.findViewById(R.id.my_id_share).setOnClickListener(this);
            fragmentView.findViewById(R.id.my_id_qr).setOnClickListener(this);
        }
        this.avatarView = fragmentView.findViewById(R.id.avatar_edit_view);
        this.avatarView.setFragment(this);
        this.avatarView.setIsMyProfilePicture(true);
        this.avatarView.setContactModel(contactService.getMe());
        this.nicknameTextView = fragmentView.findViewById(R.id.nickname);
        if (isReadonlyProfile) {
            this.fragmentView.findViewById(R.id.profile_edit).setVisibility(View.GONE);
            this.avatarView.setEditable(false);
        } else {
            this.fragmentView.findViewById(R.id.profile_edit).setVisibility(View.VISIBLE);
            this.fragmentView.findViewById(R.id.profile_edit).setOnClickListener(this);
        }
        AppCompatSpinner spinner = fragmentView.findViewById(R.id.picrelease_spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(), R.array.picrelease_choices, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setSelection(preferenceService.getProfilePicRelease());
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                int oldPosition = preferenceService.getProfilePicRelease();
                preferenceService.setProfilePicRelease(position);
                picReleaseConfImageView.setVisibility(position == PreferenceService.PROFILEPIC_RELEASE_SOME ? View.VISIBLE : View.GONE);
                if (position == PreferenceService.PROFILEPIC_RELEASE_SOME && position != oldPosition) {
                    launchProfilePictureRecipientsSelector(view);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        if (isDisabledProfilePicReleaseSettings) {
            fragmentView.findViewById(R.id.picrelease_spinner).setVisibility(View.GONE);
            fragmentView.findViewById(R.id.picrelease_config).setVisibility(View.GONE);
            fragmentView.findViewById(R.id.picrelease_text).setVisibility(View.GONE);
        }
        reloadNickname();
    }
    ListenerManager.profileListeners.add(this.profileListener);
    return fragmentView;
}

16 Source : LayoutAnimationsActivity.java
with Apache License 2.0
from REBOOTERS

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_layout_animations);
    container = new FixedGridLayout(this);
    container.setClipChildren(false);
    ((FixedGridLayout) container).setCellHeight(90);
    ((FixedGridLayout) container).setCellWidth(100);
    final LayoutTransition transitioner = new LayoutTransition();
    container.setLayoutTransition(transitioner);
    defaultAppearingAnim = transitioner.getAnimator(LayoutTransition.APPEARING);
    defaultDisappearingAnim = transitioner.getAnimator(LayoutTransition.DISAPPEARING);
    defaultChangingAppearingAnim = transitioner.getAnimator(LayoutTransition.CHANGE_APPEARING);
    defaultChangingDisappearingAnim = transitioner.getAnimator(LayoutTransition.CHANGE_DISAPPEARING);
    createCustomAnimations(transitioner);
    currentAppearingAnim = defaultAppearingAnim;
    currentDisappearingAnim = defaultDisappearingAnim;
    currentChangingAppearingAnim = defaultChangingAppearingAnim;
    currentChangingDisappearingAnim = defaultChangingDisappearingAnim;
    ViewGroup parent = (ViewGroup) findViewById(R.id.parent);
    parent.addView(container);
    parent.setClipChildren(false);
    Button addButton = (Button) findViewById(R.id.addNewButton);
    addButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Button newButton = new Button(LayoutAnimationsActivity.this);
            newButton.setPadding(5, 5, 5, 5);
            newButton.setText(String.valueOf(numButtons++));
            newButton.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    container.removeView(v);
                }
            });
            container.addView(newButton, Math.min(1, container.getChildCount()));
        }
    });
    CheckBox customAnimCB = (CheckBox) findViewById(R.id.customAnimCB);
    customAnimCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            setupTransition(transitioner);
        }
    });
    // Check for disabled animations
    CheckBox appearingCB = (CheckBox) findViewById(R.id.appearingCB);
    appearingCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            setupTransition(transitioner);
        }
    });
    CheckBox disappearingCB = (CheckBox) findViewById(R.id.disappearingCB);
    disappearingCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            setupTransition(transitioner);
        }
    });
    CheckBox changingAppearingCB = (CheckBox) findViewById(R.id.changingAppearingCB);
    changingAppearingCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            setupTransition(transitioner);
        }
    });
    CheckBox changingDisappearingCB = (CheckBox) findViewById(R.id.changingDisappearingCB);
    changingDisappearingCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            setupTransition(transitioner);
        }
    });
}

16 Source : LayoutAnimationsActivity.java
with Apache License 2.0
from REBOOTERS

private void setupTransition(LayoutTransition transition) {
    CheckBox customAnimCB = (CheckBox) findViewById(R.id.customAnimCB);
    CheckBox appearingCB = (CheckBox) findViewById(R.id.appearingCB);
    CheckBox disappearingCB = (CheckBox) findViewById(R.id.disappearingCB);
    CheckBox changingAppearingCB = (CheckBox) findViewById(R.id.changingAppearingCB);
    CheckBox changingDisappearingCB = (CheckBox) findViewById(R.id.changingDisappearingCB);
    transition.setAnimator(LayoutTransition.APPEARING, appearingCB.isChecked() ? (customAnimCB.isChecked() ? customAppearingAnim : defaultAppearingAnim) : null);
    transition.setAnimator(LayoutTransition.DISAPPEARING, disappearingCB.isChecked() ? (customAnimCB.isChecked() ? customDisappearingAnim : defaultDisappearingAnim) : null);
    transition.setAnimator(LayoutTransition.CHANGE_APPEARING, changingAppearingCB.isChecked() ? (customAnimCB.isChecked() ? customChangingAppearingAnim : defaultChangingAppearingAnim) : null);
    transition.setAnimator(LayoutTransition.CHANGE_DISAPPEARING, changingDisappearingCB.isChecked() ? (customAnimCB.isChecked() ? customChangingDisappearingAnim : defaultChangingDisappearingAnim) : null);
}

16 Source : WallpaperPickerActivity.java
with GNU General Public License v3.0
from LawnchairLauncher

/**
 * called by onCreate; this is sub-clreplaceded to overwrite WallpaperCropActivity
 */
protected void init() {
    setContentView(R.layout.wallpaper_picker);
    mCropView = findViewById(R.id.cropView);
    mCropView.setVisibility(View.INVISIBLE);
    mProgressView = findViewById(R.id.loading);
    mWallpaperScrollContainer = findViewById(R.id.wallpaper_scroll_container);
    mWallpaperStrip = findViewById(R.id.wallpaper_strip);
    mCropView.setTouchCallback(new ToggleOnTapCallback(mWallpaperStrip));
    mWallpaperParallaxOffset = getIntent().getFloatExtra(Utilities.EXTRA_WALLPAPER_OFFSET, 0);
    mWallpapersView = findViewById(R.id.wallpaper_list);
    // Populate the saved wallpapers
    mSavedImages = new SavedWallpaperImages(this);
    populateWallpapers(mWallpapersView, mSavedImages.loadThumbnailsAndImageIdList(), true);
    // Load live wallpapers asynchronously
    new LiveWallpaperInfo.LoaderTask(this) {

        @Override
        protected void onPostExecute(List<LiveWallpaperInfo> result) {
            populateWallpapers((LinearLayout) findViewById(R.id.live_wallpaper_list), result, false);
            initializeScrollForRtl();
            updateTileIndices();
        }
    }.execute();
    // Populate the third-party wallpaper pickers
    populateWallpapers((LinearLayout) findViewById(R.id.third_party_wallpaper_list), ThirdPartyWallpaperInfo.getAll(this), false);
    // Add a tile for the Gallery
    LinearLayout masterWallpaperList = findViewById(R.id.master_wallpaper_list);
    masterWallpaperList.addView(createTileView(masterWallpaperList, new PickImageInfo(), false), 0);
    // Select the first item; wait for a layout preplaced so that we initialize the dimensions of
    // cropView or the defaultWallpaperView first
    mCropView.addOnLayoutChangeListener(new OnLayoutChangeListener() {

        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
            if ((right - left) > 0 && (bottom - top) > 0) {
                if (mSelectedIndex >= 0 && mSelectedIndex < mWallpapersView.getChildCount()) {
                    onClick(mWallpapersView.getChildAt(mSelectedIndex));
                    setSystemWallpaperVisiblity(false);
                }
                v.removeOnLayoutChangeListener(this);
            }
        }
    });
    updateTileIndices();
    // Update the scroll for RTL
    initializeScrollForRtl();
    // Create smooth layout transitions for when items are deleted
    final LayoutTransition transitioner = new LayoutTransition();
    transitioner.setDuration(200);
    transitioner.setStartDelay(LayoutTransition.CHANGE_DISAPPEARING, 0);
    transitioner.setAnimator(LayoutTransition.DISAPPEARING, null);
    mWallpapersView.setLayoutTransition(transitioner);
    // Action bar
    // Show the custom action bar view
    final ActionBar actionBar = getActionBar();
    actionBar.setCustomView(R.layout.actionbar_set_wallpaper);
    actionBar.getCustomView().setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Ensure that a tile is selected and loaded.
            if (mSelectedTile != null && mCropView.getTileSource() != null) {
                // Prevent user from selecting any new tile.
                mWallpaperStrip.setVisibility(View.GONE);
                actionBar.hide();
                WallpaperTileInfo info = (WallpaperTileInfo) mSelectedTile.getTag();
                info.onSave(WallpaperPickerActivity.this);
            } else {
                // This case shouldn't be possible, since "Set wallpaper" is disabled
                // until user clicks on a replacedle.
                Log.w(TAG, "\"Set wallpaper\" was clicked when no tile was selected");
            }
        }
    });
    mSetWallpaperButton = findViewById(R.id.set_wallpaper_button);
}

16 Source : LayoutAnimations.java
with Apache License 2.0
from jiyouliang

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_animations);
    container = new FixedGridLayout(this);
    container.setClipChildren(false);
    ((FixedGridLayout) container).setCellHeight(90);
    ((FixedGridLayout) container).setCellWidth(100);
    final LayoutTransition transitioner = new LayoutTransition();
    container.setLayoutTransition(transitioner);
    defaultAppearingAnim = transitioner.getAnimator(LayoutTransition.APPEARING);
    defaultDisappearingAnim = transitioner.getAnimator(LayoutTransition.DISAPPEARING);
    defaultChangingAppearingAnim = transitioner.getAnimator(LayoutTransition.CHANGE_APPEARING);
    defaultChangingDisappearingAnim = transitioner.getAnimator(LayoutTransition.CHANGE_DISAPPEARING);
    createCustomAnimations(transitioner);
    currentAppearingAnim = defaultAppearingAnim;
    currentDisappearingAnim = defaultDisappearingAnim;
    currentChangingAppearingAnim = defaultChangingAppearingAnim;
    currentChangingDisappearingAnim = defaultChangingDisappearingAnim;
    ViewGroup parent = (ViewGroup) findViewById(R.id.parent);
    parent.addView(container);
    parent.setClipChildren(false);
    Button addButton = (Button) findViewById(R.id.addNewButton);
    addButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Button newButton = new Button(LayoutAnimations.this);
            newButton.setText(String.valueOf(numButtons++));
            newButton.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    container.removeView(v);
                }
            });
            container.addView(newButton, Math.min(1, container.getChildCount()));
        }
    });
    CheckBox customAnimCB = (CheckBox) findViewById(R.id.customAnimCB);
    customAnimCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            setupTransition(transitioner);
        }
    });
    // Check for disabled animations
    CheckBox appearingCB = (CheckBox) findViewById(R.id.appearingCB);
    appearingCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            setupTransition(transitioner);
        }
    });
    CheckBox disappearingCB = (CheckBox) findViewById(R.id.disappearingCB);
    disappearingCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            setupTransition(transitioner);
        }
    });
    CheckBox changingAppearingCB = (CheckBox) findViewById(R.id.changingAppearingCB);
    changingAppearingCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            setupTransition(transitioner);
        }
    });
    CheckBox changingDisappearingCB = (CheckBox) findViewById(R.id.changingDisappearingCB);
    changingDisappearingCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            setupTransition(transitioner);
        }
    });
}

16 Source : RepostAndShareActivity.java
with MIT License
from jianliaoim

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_share_handle);
    ButterKnife.inject(this);
    BusProvider.getInstance().register(this);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setreplacedle(R.string.send_to);
    presenter = new TeamPresenter(this);
    teamId = BizLogic.getTeamId();
    currentTeam = BizLogic.getTeam();
    LayoutTransition lt = new LayoutTransition();
    lt.setDuration(150);
    Intent intent = getIntent();
    messageId = intent.getStringExtra("id");
    favoritesIds = intent.getStringArrayExtra("favoritesIds");
    final Uri uri = getIntent().getParcelableExtra(Intent.EXTRA_STREAM);
    if (uri != null) {
        shareFile = new File(FileUtil.getFilePath(this, uri));
    }
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    adapter = new RepostAndShareAdapter();
    teamAdapter = new TeamAdapter(this);
    adapter.setOnItemClickListener(this);
    recyclerView.setAdapter(adapter);
    recyclerView.addOnScrollListener(listener);
    listView.setOnItemClickListener(this);
    listView.setAdapter(teamAdapter);
    layoutTeam.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            animate();
        }
    });
    mask.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            animate();
        }
    });
    if (!BizLogic.isNetworkConnected()) {
        MainApp.showToastMsg(R.string.notification_network);
    } else if (!BizLogic.isLogin()) {
        TransactionUtil.goTo(this, Oauth2Activity.clreplaced, true);
        MainApp.showToastMsg(R.string.notification_login);
    } else if (!BizLogic.hasChosenTeam()) {
        TransactionUtil.goTo(this, ChooseTeamActivity.clreplaced, true);
        MainApp.showToastMsg(R.string.notification_choose_team);
    } else {
        presenter.getTeamDetail(BizLogic.getTeamId());
        tvTeamName.setText(BizLogic.getTeamName());
        presenter.getTeams();
    }
}

16 Source : GiftControl.java
with Apache License 2.0
from DyncKathline

/**
 * @param giftLayoutParent 存放礼物控件的父容器
 * @param giftLayoutNums   礼物控件的数量
 * @return
 */
public GiftControl setGiftLayout(LinearLayout giftLayoutParent, @NonNull int giftLayoutNums) {
    if (giftLayoutNums <= 0) {
        throw new IllegalArgumentException("GiftFrameLayout数量必须大于0");
    }
    if (giftLayoutParent.getChildCount() > 0) {
        // 如果父容器没有子孩子,就进行添加
        return this;
    }
    mGiftLayoutParent = giftLayoutParent;
    mGiftLayoutMaxNums = giftLayoutNums;
    LayoutTransition transition = new LayoutTransition();
    transition.setAnimator(LayoutTransition.CHANGE_APPEARING, transition.getAnimator(LayoutTransition.CHANGE_APPEARING));
    transition.setAnimator(LayoutTransition.APPEARING, transition.getAnimator(LayoutTransition.APPEARING));
    transition.setAnimator(LayoutTransition.DISAPPEARING, transition.getAnimator(LayoutTransition.CHANGE_APPEARING));
    transition.setAnimator(LayoutTransition.CHANGE_DISAPPEARING, transition.getAnimator(LayoutTransition.DISAPPEARING));
    mGiftLayoutParent.setLayoutTransition(transition);
    return this;
}

16 Source : LayoutTransitionFragment.java
with Apache License 2.0
from chiclaim

private LayoutTransition createTransition() {
    LayoutTransition mTransitioner = new LayoutTransition();
    // 入场动画:view在这个容器中消失时触发的动画
    ObjectAnimator animIn = ObjectAnimator.ofFloat(null, "rotationY", 0f, 360f, 0f);
    mTransitioner.setAnimator(LayoutTransition.APPEARING, animIn);
    // 出场动画:view显示时的动画
    ObjectAnimator animOut = ObjectAnimator.ofFloat(null, "rotation", 0f, 90f, 0f);
    mTransitioner.setAnimator(LayoutTransition.DISAPPEARING, animOut);
    return mTransitioner;
}

15 Source : LayoutAnimationsActivity.java
with Apache License 2.0
from REBOOTERS

private void createCustomAnimations(LayoutTransition transition) {
    // Changing while Adding
    PropertyValuesHolder pvhLeft = PropertyValuesHolder.ofInt("left", 0, 1);
    PropertyValuesHolder pvhTop = PropertyValuesHolder.ofInt("top", 0, 1);
    PropertyValuesHolder pvhRight = PropertyValuesHolder.ofInt("right", 0, 1);
    PropertyValuesHolder pvhBottom = PropertyValuesHolder.ofInt("bottom", 0, 1);
    PropertyValuesHolder pvhScaleX = PropertyValuesHolder.ofFloat("scaleX", 1f, 0f, 1f);
    PropertyValuesHolder pvhScaleY = PropertyValuesHolder.ofFloat("scaleY", 1f, 0f, 1f);
    customChangingAppearingAnim = ObjectAnimator.ofPropertyValuesHolder(this, pvhLeft, pvhTop, pvhRight, pvhBottom, pvhScaleX, pvhScaleY).setDuration(transition.getDuration(LayoutTransition.CHANGE_APPEARING));
    customChangingAppearingAnim.addListener(new AnimatorListenerAdapter() {

        public void onAnimationEnd(Animator anim) {
            View view = (View) ((ObjectAnimator) anim).getTarget();
            view.setScaleX(1f);
            view.setScaleY(1f);
        }
    });
    // Changing while Removing
    Keyframe kf0 = Keyframe.ofFloat(0f, 0f);
    Keyframe kf1 = Keyframe.ofFloat(.9999f, 360f);
    Keyframe kf2 = Keyframe.ofFloat(1f, 0f);
    PropertyValuesHolder pvhRotation = PropertyValuesHolder.ofKeyframe("rotation", kf0, kf1, kf2);
    customChangingDisappearingAnim = ObjectAnimator.ofPropertyValuesHolder(this, pvhLeft, pvhTop, pvhRight, pvhBottom, pvhRotation).setDuration(transition.getDuration(LayoutTransition.CHANGE_DISAPPEARING));
    customChangingDisappearingAnim.addListener(new AnimatorListenerAdapter() {

        public void onAnimationEnd(Animator anim) {
            View view = (View) ((ObjectAnimator) anim).getTarget();
            view.setRotation(0f);
        }
    });
    // Adding
    customAppearingAnim = ObjectAnimator.ofFloat(null, "rotationY", 90f, 0f).setDuration(transition.getDuration(LayoutTransition.APPEARING));
    customAppearingAnim.addListener(new AnimatorListenerAdapter() {

        public void onAnimationEnd(Animator anim) {
            View view = (View) ((ObjectAnimator) anim).getTarget();
            view.setRotationY(0f);
        }
    });
    // Removing
    customDisappearingAnim = ObjectAnimator.ofFloat(null, "rotationX", 0f, 90f).setDuration(transition.getDuration(LayoutTransition.DISAPPEARING));
    customDisappearingAnim.addListener(new AnimatorListenerAdapter() {

        public void onAnimationEnd(Animator anim) {
            View view = (View) ((ObjectAnimator) anim).getTarget();
            view.setRotationX(0f);
        }
    });
}

15 Source : MainActivity.java
with Apache License 2.0
from felix1022224

// 初始化AppBarLayout
private void initAppBarLayout() {
    LayoutTransition mTransition = new LayoutTransition();
    /**
     * 添加View时过渡动画效果
     */
    ObjectAnimator addAnimator = ObjectAnimator.ofFloat(null, "translationY", 0, 1.f).setDuration(mTransition.getDuration(LayoutTransition.APPEARING));
    mTransition.setAnimator(LayoutTransition.APPEARING, addAnimator);
    // header layout height
    final int headerHeight = getResources().getDimensionPixelOffset(R.dimen.header_height);
    mAppBarLayout = (AppBarLayout) findViewById(R.id.appbar);
    mAppBarLayout.setLayoutTransition(mTransition);
    mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {

        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
            verticalOffset = Math.abs(verticalOffset);
            if (verticalOffset >= headerHeight) {
                isHideHeaderLayout = true;
                // 当偏移量超过顶部layout的高度时,我们认为他已经完全移动出屏幕了
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        AppBarLayout.LayoutParams mParams = (AppBarLayout.LayoutParams) headerLayout.getLayoutParams();
                        mParams.setScrollFlags(0);
                        headerLayout.setLayoutParams(mParams);
                        headerLayout.setVisibility(View.GONE);
                    }
                }, 100);
            }
        }
    });
}

13 Source : MediaVideoFragment.java
with Apache License 2.0
from saket

@Override
public void onViewCreated(View fragmentLayout, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(fragmentLayout, savedInstanceState);
    // Make the video flick-dismissible.
    setupFlickGestures(flickDismissViewGroup);
    // TODO: Use Window insets instead of manually calculating this:
    // Keep the video below the status bar and above the control buttons.
    // noinspection ConstantConditions
    ((MediaFragmentCallbacks) getActivity()).optionButtonsHeight().takeUntil(lifecycle().onDestroy().ignoreElements()).subscribe(optionButtonsHeight -> {
        int statusBarHeight = Views.statusBarHeight(getResources());
        Views.setPaddingVertical(contentViewFlipper, contentViewFlipper.getPaddingTop() + statusBarHeight, contentViewFlipper.getPaddingBottom() + optionButtonsHeight);
    }, error -> {
        ResolvedError resolvedError = errorResolver.get().resolve(error);
        resolvedError.ifUnknown(() -> Timber.e(error, "Error while trying to get option buttons' height"));
    });
    exoPlayerManager = ExoPlayerManager.newInstance(videoView);
    exoPlayerManager.manageLifecycle(lifecycle()).ambWith(lifecycle().onDestroyCompletable()).subscribe();
    videoControlsView = new MediaViewerVideoControlsView(getActivity());
    videoView.setControls(videoControlsView);
    videoControlsView.showVideoState(MediaViewerVideoControlsView.VideoState.PREPARING);
    // Toggle immersive when the user clicks anywhere.
    // noinspection ConstantConditions
    View.OnClickListener immersiveToggleListener = o -> ((MediaFragmentCallbacks) getActivity()).toggleImmersiveMode();
    videoControlsView.setOnClickListener(immersiveToggleListener);
    flickDismissViewGroup.setOnClickListener(immersiveToggleListener);
    // The preview image takes time to be drawn. Fade the video in slowly.
    LayoutTransition layoutTransition = ((ViewGroup) videoView.getParent()).getLayoutTransition();
    videoView.setLayoutTransition(layoutTransition);
    View textureViewContainer = ((ViewGroup) exoPlayerManager.getTextureView().getParent());
    textureViewContainer.setVisibility(View.INVISIBLE);
    videoView.setOnPreparedListener(() -> {
        textureViewContainer.setVisibility(View.VISIBLE);
        videoControlsView.showVideoState(MediaViewerVideoControlsView.VideoState.PREPARED);
        // Auto-play when this Fragment becomes visible.
        fragmentVisibleToUserStream.take(1).takeUntil(lifecycle().onDestroy()).subscribe(visibleToUser -> {
            if (!visibleToUser) {
                exoPlayerManager.pausePlayback();
            } else {
                exoPlayerManager.startPlayback();
            }
        });
    });
    // VideoView internally sets its height to match-parent. Forcefully resize it to match the video height.
    exoPlayerManager.setOnVideoSizeChangeListener((videoWidth, videoHeight) -> {
        ((MediaFragmentCallbacks) getActivity()).optionButtonsHeight().takeUntil(lifecycle().onDestroyCompletable()).subscribe(optionButtonsHeight -> {
            // TODO: Use Window insets instead of manually calculating this:
            ViewGroup parent = contentViewFlipper;
            int parentWidth = parent.getWidth();
            int parentHeight = parent.getHeight();
            int videoControlsHeight = videoControlsView.heightOfControlButtons();
            float resizeFactorToFillHorizontalSpace = (float) parentWidth / videoWidth;
            int resizedHeight = (int) (videoHeight * resizeFactorToFillHorizontalSpace) + videoControlsHeight;
            int verticalSpaceAvailable = parentHeight - Views.getPaddingVertical(parent);
            Views.setDimensions(videoView, parentWidth, Math.min(resizedHeight, verticalSpaceAvailable));
        }, error -> {
            ResolvedError resolvedError = errorResolver.get().resolve(error);
            resolvedError.ifUnknown(() -> Timber.e(error, "Error while trying to get option buttons' height"));
        });
    });
    long startPositionMillis;
    if (savedInstanceState != null) {
        startPositionMillis = savedInstanceState.getLong(KEY_SEEK_POSITION_MILLIS);
    } else if (mediaAlbumItem.mediaLink() instanceof MediaLinkWithStartingPosition) {
        startPositionMillis = ((MediaLinkWithStartingPosition) mediaAlbumItem.mediaLink()).startingPositionMillis();
    } else {
        startPositionMillis = 0;
    }
    // Rewind by a small duration so that the user doesn't miss anything during a transition.
    startPositionMillis = Math.max(0, startPositionMillis - 1_000);
    loadVideo(startPositionMillis);
}

13 Source : DraggableCardFragment.java
with Apache License 2.0
from material-components

@Override
public View onCreateDemoView(LayoutInflater layoutInflater, @Nullable ViewGroup viewGroup, @Nullable Bundle bundle) {
    View view = layoutInflater.inflate(R.layout.cat_card_draggable_fragment, viewGroup, false);
    DraggableCoordinatorLayout container = (DraggableCoordinatorLayout) view;
    LayoutTransition transition = ((CoordinatorLayout) view).getLayoutTransition();
    if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
        transition.enableTransitionType(LayoutTransition.CHANGING);
    }
    card = view.findViewById(R.id.draggable_card);
    card.setAccessibilityDelegate(cardDelegate);
    container.addDraggableChild(card);
    if (VERSION.SDK_INT < VERSION_CODES.LOLLIPOP) {
        return view;
    }
    container.setViewDragListener(new ViewDragListener() {

        @Override
        public void onViewCaptured(@NonNull View view, int i) {
            card.setDragged(true);
        }

        @Override
        public void onViewReleased(@NonNull View view, float v, float v1) {
            card.setDragged(false);
        }
    });
    return view;
}

12 Source : LayoutTransitionFragment.java
with Apache License 2.0
from chiclaim

private LayoutTransition createTransitionChange() {
    LayoutTransition mTransitioner = new LayoutTransition();
    // 入场动画:view在这个容器中消失时触发的动画
    ObjectAnimator animIn = ObjectAnimator.ofFloat(null, "rotationY", 0f, 360f, 0f);
    mTransitioner.setAnimator(LayoutTransition.APPEARING, animIn);
    // 出场动画:view显示时的动画
    ObjectAnimator animOut = ObjectAnimator.ofFloat(null, "rotation", 0f, 90f, 0f);
    mTransitioner.setAnimator(LayoutTransition.DISAPPEARING, animOut);
    PropertyValuesHolder pvhLeft = PropertyValuesHolder.ofInt("left", 0, 100, 0);
    PropertyValuesHolder pvhTop = PropertyValuesHolder.ofInt("top", 0, 0);
    PropertyValuesHolder pvhRight = PropertyValuesHolder.ofInt("right", 0, 0);
    PropertyValuesHolder pvhBottom = PropertyValuesHolder.ofInt("bottom", 0, 0);
    Animator changeAppearAnimator = ObjectAnimator.ofPropertyValuesHolder(layoutTransitionGroup, pvhLeft, pvhTop, pvhRight, pvhBottom);
    mTransitioner.setAnimator(LayoutTransition.CHANGE_APPEARING, changeAppearAnimator);
    /*
            1, LayoutTransition.CHANGE_APPEARING/CHANGE_DISAPPEARING 必须配合PropertyValuesHolder使用才能有效果(使用ObjectAnimator无效).
         */
    return mTransitioner;
}

10 Source : ViewGroupUtilsApi14.java
with Apache License 2.0
from androidx

static void suppressLayout(@NonNull ViewGroup group, boolean suppress) {
    // Prepare the empty LayoutTransition
    if (sEmptyLayoutTransition == null) {
        sEmptyLayoutTransition = new LayoutTransition() {

            @Override
            public boolean isChangingLayout() {
                return true;
            }
        };
        sEmptyLayoutTransition.setAnimator(LayoutTransition.APPEARING, null);
        sEmptyLayoutTransition.setAnimator(LayoutTransition.CHANGE_APPEARING, null);
        sEmptyLayoutTransition.setAnimator(LayoutTransition.CHANGE_DISAPPEARING, null);
        sEmptyLayoutTransition.setAnimator(LayoutTransition.DISAPPEARING, null);
        sEmptyLayoutTransition.setAnimator(LAYOUT_TRANSITION_CHANGING, null);
    }
    if (suppress) {
        // Save the current LayoutTransition
        final LayoutTransition layoutTransition = group.getLayoutTransition();
        if (layoutTransition != null) {
            if (layoutTransition.isRunning()) {
                cancelLayoutTransition(layoutTransition);
            }
            if (layoutTransition != sEmptyLayoutTransition) {
                group.setTag(R.id.transition_layout_save, layoutTransition);
            }
        }
        // Suppress the layout
        group.setLayoutTransition(sEmptyLayoutTransition);
    } else {
        // Thaw the layout suppression
        group.setLayoutTransition(null);
        // Request layout if necessary
        if (!sLayoutSuppressedFieldFetched) {
            try {
                sLayoutSuppressedField = ViewGroup.clreplaced.getDeclaredField("mLayoutSuppressed");
                sLayoutSuppressedField.setAccessible(true);
            } catch (NoSuchFieldException e) {
                Log.i(TAG, "Failed to access mLayoutSuppressed field by reflection");
            }
            sLayoutSuppressedFieldFetched = true;
        }
        boolean layoutSuppressed = false;
        if (sLayoutSuppressedField != null) {
            try {
                layoutSuppressed = sLayoutSuppressedField.getBoolean(group);
                if (layoutSuppressed) {
                    sLayoutSuppressedField.setBoolean(group, false);
                }
            } catch (IllegalAccessException e) {
                Log.i(TAG, "Failed to get mLayoutSuppressed field by reflection");
            }
        }
        if (layoutSuppressed) {
            group.requestLayout();
        }
        // Restore the saved LayoutTransition
        final LayoutTransition layoutTransition = (LayoutTransition) group.getTag(R.id.transition_layout_save);
        if (layoutTransition != null) {
            group.setTag(R.id.transition_layout_save, null);
            group.setLayoutTransition(layoutTransition);
        }
    }
}

8 Source : TransitionProvider.java
with Apache License 2.0
from LightSun

public static LayoutTransition createTransition(Object target) {
    LayoutTransition mLayoutTransition = new LayoutTransition();
    mLayoutTransition.setStagger(LayoutTransition.CHANGE_APPEARING, 30);
    mLayoutTransition.setStagger(LayoutTransition.CHANGE_DISAPPEARING, 30);
    // 设置每个动画持续的时间
    mLayoutTransition.setDuration(300);
    /**
     * Add Button
     * LayoutTransition.APPEARING
     * 增加一个Button时,设置该Button的动画效果
     */
    ObjectAnimator mAnimatorAppearing = ObjectAnimator.ofFloat(null, "rotationY", 90.0f, 0.0f).setDuration(mLayoutTransition.getDuration(LayoutTransition.APPEARING));
    // 为LayoutTransition设置动画及动画类型
    mLayoutTransition.setAnimator(LayoutTransition.APPEARING, mAnimatorAppearing);
    mAnimatorAppearing.addListener(new AnimatorListenerAdapter() {

        @Override
        public void onAnimationEnd(Animator animation) {
            // TODO Auto-generated method stub
            super.onAnimationEnd(animation);
            View view = (View) ((ObjectAnimator) animation).getTarget();
            view.setRotationY(0.0f);
        }
    });
    /**
     * Add Button
     * LayoutTransition.CHANGE_APPEARING
     * 当增加一个Button时,设置其他Button的动画效果
     */
    PropertyValuesHolder pvhLeft = PropertyValuesHolder.ofInt("left", 0, 1);
    PropertyValuesHolder pvhTop = PropertyValuesHolder.ofInt("top", 0, 1);
    PropertyValuesHolder pvhRight = PropertyValuesHolder.ofInt("right", 0, 1);
    PropertyValuesHolder pvhBottom = PropertyValuesHolder.ofInt("bottom", 0, 1);
    PropertyValuesHolder mHolderScaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f, 0.0f, 1.0f);
    PropertyValuesHolder mHolderScaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f, 0.0f, 1.0f);
    ObjectAnimator mObjectAnimatorChangeAppearing = ObjectAnimator.ofPropertyValuesHolder(target, pvhLeft, pvhTop, pvhRight, pvhBottom, mHolderScaleX, mHolderScaleY).setDuration(mLayoutTransition.getDuration(LayoutTransition.CHANGE_APPEARING));
    mLayoutTransition.setAnimator(LayoutTransition.CHANGE_APPEARING, mObjectAnimatorChangeAppearing);
    mObjectAnimatorChangeAppearing.addListener(new AnimatorListenerAdapter() {

        @Override
        public void onAnimationEnd(Animator animation) {
            // TODO Auto-generated method stub
            super.onAnimationEnd(animation);
            View view = (View) ((ObjectAnimator) animation).getTarget();
            view.setScaleX(1f);
            view.setScaleY(1f);
        }
    });
    /**
     * Delete Button
     * LayoutTransition.DISAPPEARING
     * 当删除一个Button时,设置该Button的动画效果
     */
    ObjectAnimator mObjectAnimatorDisAppearing = ObjectAnimator.ofFloat(null, "rotationX", 0.0f, 90.0f).setDuration(mLayoutTransition.getDuration(LayoutTransition.DISAPPEARING));
    mLayoutTransition.setAnimator(LayoutTransition.DISAPPEARING, mObjectAnimatorDisAppearing);
    mObjectAnimatorDisAppearing.addListener(new AnimatorListenerAdapter() {

        @Override
        public void onAnimationEnd(Animator animation) {
            // TODO Auto-generated method stub
            super.onAnimationEnd(animation);
            View view = (View) ((ObjectAnimator) animation).getTarget();
            view.setRotationX(0.0f);
        }
    });
    /**
     * Delete Button
     * LayoutTransition.CHANGE_DISAPPEARING
     * 当删除一个Button时,设置其它Button的动画效果
     */
    // Keyframe 对象中包含了一个时间/属性值的键值对,用于定义某个时刻的动画状态。
    Keyframe mKeyframeStart = Keyframe.ofFloat(0.0f, 0.0f);
    Keyframe mKeyframeMiddle = Keyframe.ofFloat(0.5f, 180.0f);
    Keyframe mKeyframeEndBefore = Keyframe.ofFloat(0.999f, 360.0f);
    Keyframe mKeyframeEnd = Keyframe.ofFloat(1.0f, 0.0f);
    PropertyValuesHolder mPropertyValuesHolder = PropertyValuesHolder.ofKeyframe("rotation", mKeyframeStart, mKeyframeMiddle, mKeyframeEndBefore, mKeyframeEnd);
    ObjectAnimator mObjectAnimatorChangeDisAppearing = ObjectAnimator.ofPropertyValuesHolder(target, pvhLeft, pvhTop, pvhRight, pvhBottom, mPropertyValuesHolder).setDuration(mLayoutTransition.getDuration(LayoutTransition.CHANGE_DISAPPEARING));
    mLayoutTransition.setAnimator(LayoutTransition.CHANGE_DISAPPEARING, mObjectAnimatorChangeDisAppearing);
    mObjectAnimatorChangeDisAppearing.addListener(new AnimatorListenerAdapter() {

        @Override
        public void onAnimationEnd(Animator animation) {
            // TODO Auto-generated method stub
            super.onAnimationEnd(animation);
            View view = (View) ((ObjectAnimator) animation).getTarget();
            view.setRotation(0.0f);
        }
    });
    return mLayoutTransition;
}