LayoutTransition for LinearLayout with wrap_content - android

I'm trying to animate the add/remove actions of the views of an LinearLayout that has it's height set as wrap_content.
Currently I've tried setting android:animateLayoutChanges="true" for the LinearLayout and programmatically enabling the transitions like this:
LayoutTransition transition = new LayoutTransition();
transition.setDuration(300);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
transition.enableTransitionType(LayoutTransition.APPEARING);
transition.enableTransitionType(LayoutTransition.DISAPPEARING);
transition.setAnimateParentHierarchy(true);
}
container.setLayoutTransition(transition);
The Appearing seems to work very smooth and it animates and resizes as I want.
The issue I'm having is with Disappearing as the LinearLayout container is resized before the remove animation is finished.
I've also tried playing around with the setAnimateParentHierarchy() and it doesn't seem to really affect on how and when the resize of the container is done.

A simple solution is to set a layout transition to the first ancestor which does not use wrap_content.
The following code finds the correct anscestor, sets the required animation and restore the original LayoutTransition (if any existed) at the end of the animation.
Call this method in your code where you perform the add/remove actions.
None of your code which is included in the question is required.
Note: This solution will only work for SDK >= JELLY_BEAN.
private static void setHeightChangeAnimation(ViewGroup animatedLayout) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
ViewGroup vg = animatedLayout;
while (vg instanceof ViewGroup) {
vg = (ViewGroup) vg.getParent();
if (vg instanceof ViewGroup && vg.getLayoutParams().height != LayoutParams.WRAP_CONTENT) {
LayoutTransition animatedLayoutLt = animatedLayout.getLayoutTransition();
LayoutTransition lt = new LayoutTransition();
lt.enableTransitionType(LayoutTransition.CHANGING);
lt.setDuration(animatedLayoutLt.getDuration(LayoutTransition.CHANGE_APPEARING));
lt.setStartDelay(LayoutTransition.CHANGING, animatedLayoutLt.getStartDelay(LayoutTransition.APPEARING));
final ViewGroup finalVg = vg;
final LayoutTransition oldLt = finalVg.getLayoutTransition();
lt.addTransitionListener(new LayoutTransition.TransitionListener() {
public void startTransition(LayoutTransition transition, ViewGroup container, View view, int transitionType) {}
public void endTransition(LayoutTransition transition, ViewGroup container, View view, int transitionType) {
finalVg.setLayoutTransition(oldLt);
}
});
finalVg.setLayoutTransition(lt);
break;
}
}
}
}
And use this to call:
setHeightChangeAnimation(yourAnimatedLinearLayout);

Related

Send a view to back in Relative Layout

I am having so many views to in a relative layout which is able to zoom and rotate. what I am trying to achieve is, when I long click a view it should able to send that particular view to last .
what I do is
private void moveToBack(View currentView) {
ViewGroup vg = ((ViewGroup) currentView.getParent());
for (int i = 0; i < vg.getChildCount(); i++) {
View v = vg.getChildAt(i);
if (!v.equals(currentView)) {
vg.bringChildToFront(v);
break;
}
}
}
This will set the another view above the selected view I need to send that particular view to last. MIn sdk is 17 and I can't change that.
We don't have something like bringToback() method so only we could modify the order of childviews. I tried once to achieve it using tricky way :
public void sendViewToBack(View child) {
final ViewGroup mParent = (ViewGroup)child.getParent();
if (null != mParent) {
mParent.removeView(child);
mParent.addView(child, 0);
}
}

BottomSheetDialogFragment - How to set expanded height (or min top offset)

I create a BottomSheetDialogFragment and I want to adjust it's maximum expanded height. How can I do that? I can retrieve the BottomSheetBehaviour but all I can find is a setter for the peek height but nothing for the expanded height.
public class DialogMediaDetails extends BottomSheetDialogFragment
{
#Override
public void setupDialog(Dialog dialog, int style)
{
super.setupDialog(dialog, style);
View view = View.inflate(getContext(), R.layout.dialog_media_details, null);
dialog.setContentView(view);
...
View bottomSheet = dialog.findViewById(R.id.design_bottom_sheet);
BottomSheetBehavior behavior = BottomSheetBehavior.from(bottomSheet);
behavior.setPeekHeight(...);
// how to set maximum expanded height???? Or a minimum top offset?
}
}
EDIT
Why do I need that? Because I show a BottomSheet Dialog in a full screen activity and it looks bad if the BottomSheet leaves a space on top...
The height is being wrapped because the inflated view is added to the FrameLayout which has layout_height=wrap_content. See FrameLayout (R.id.design_bottom_sheet) at https://github.com/dandar3/android-support-design/blob/master/res/layout/design_bottom_sheet_dialog.xml.
The class below makes the bottom sheet full screen, background transparent, and fully expanded to the top.
public class FullScreenBottomSheetDialogFragment extends BottomSheetDialogFragment {
#CallSuper
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
}
#Override
public void onStart() {
super.onStart();
Dialog dialog = getDialog();
if (dialog != null) {
View bottomSheet = dialog.findViewById(R.id.design_bottom_sheet);
bottomSheet.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
}
View view = getView();
view.post(() -> {
View parent = (View) view.getParent();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) (parent).getLayoutParams();
CoordinatorLayout.Behavior behavior = params.getBehavior();
BottomSheetBehavior bottomSheetBehavior = (BottomSheetBehavior) behavior;
bottomSheetBehavior.setPeekHeight(view.getMeasuredHeight());
((View)bottomSheet.getParent()).setBackgroundColor(Color.TRANSPARENT)
});
}
}
--- EDIT Aug 30, 2018 ---
I realized a year later that the background was colored on the wrong view. This dragged the background along with the content while a user was dragging the dialog.
I fixed it so that the parent view of the bottom sheet is colored.
I found a much simpler answer; in your example where you obtain the FrameLayout for the bottom sheet using this code
View bottomSheet = dialog.findViewById(R.id.design_bottom_sheet);
you can then set the height on the layout params for that View to whatever height you want to set the expanded height to.
bottomSheet.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
BIG UPDATE
Avoiding duplicated code I'm giving a link to the full answer in where you can find all the explanations about how to get full behavior like Google Maps.
I want to adjust its maximum expanded height. How can I do that?
Both BottomSheet and BottomSheetDialogFragment use a BottomSheetBehavior that you can found in Support Library 23.x
That Java class has 2 different uses for mMinOffset, one of them is used to define the area of the parent it will use to draw his content (maybe a NestedScrollView). And the other use is for defining the expanded anchor point, I mean, if you slide it up to form STATE_COLLAPSEDit will animate your BottomSheetuntil he reached this anchor point BUT if you can still keep sliding up to cover all parent height (CoordiantorLayout Height).
If you took a look at BottomSheetDialog you will see this method:
private View wrapInBottomSheet(int layoutResId, View view, ViewGroup.LayoutParams params) {
final CoordinatorLayout coordinator = (CoordinatorLayout) View.inflate(getContext(),
android.support.design.R.layout.design_bottom_sheet_dialog, null);
if (layoutResId != 0 && view == null) {
view = getLayoutInflater().inflate(layoutResId, coordinator, false);
}
FrameLayout bottomSheet = (FrameLayout) coordinator.findViewById(android.support.design.R.id.design_bottom_sheet);
BottomSheetBehavior.from(bottomSheet).setBottomSheetCallback(mBottomSheetCallback);
if (params == null) {
bottomSheet.addView(view);
} else {
bottomSheet.addView(view, params);
}
// We treat the CoordinatorLayout as outside the dialog though it is technically inside
if (shouldWindowCloseOnTouchOutside()) {
final View finalView = view;
coordinator.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (isShowing() &&
MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_UP &&
!coordinator.isPointInChildBounds(finalView,
(int) event.getX(), (int) event.getY())) {
cancel();
return true;
}
return false;
}
});
}
return coordinator;
}
No idea which one of those 2 behaviors you want but if you need the second one follow those steps:
Create a Java class and extend it from CoordinatorLayout.Behavior<V>
Copy paste code from the default BottomSheetBehavior file to your new one.
Modify the method clampViewPositionVertical with the following code:
#Override
public int clampViewPositionVertical(View child, int top, int dy) {
return constrain(top, mMinOffset, mHideable ? mParentHeight : mMaxOffset);
}
int constrain(int amount, int low, int high) {
return amount < low ? low : (amount > high ? high : amount);
}
Add a new state
public static final int STATE_ANCHOR_POINT = X;
Modify the next methods: onLayoutChild, onStopNestedScroll, BottomSheetBehavior<V> from(V view) and setState (optional)
And here is how it looks like
[]
Its works for me. Add code on BottomSheetDialogFragment's onViewCreated() methode
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
view.viewTreeObserver.removeOnGlobalLayoutListener(this)
val dialog = dialog as BottomSheetDialog
val bottomSheet = dialog.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) as FrameLayout?
val behavior = BottomSheetBehavior.from(bottomSheet!!)
behavior.state = BottomSheetBehavior.STATE_EXPANDED
val newHeight = activity?.window?.decorView?.measuredHeight
val viewGroupLayoutParams = bottomSheet.layoutParams
viewGroupLayoutParams.height = newHeight ?: 0
bottomSheet.layoutParams = viewGroupLayoutParams
}
})
dialogView = view
}
Don't forget to remove viewTreeObserver.
override fun onDestroyView() {
dialogView?.viewTreeObserver?.addOnGlobalLayoutListener(null)
super.onDestroyView()
}
Get reference to sheet behavior,
private val behavior by lazy { (dialog as BottomSheetDialog).behavior }
turn fitToContents off and set expandedOffset to desired pixels.
behavior.isFitToContents = false
behavior.expandedOffset = 100
Kotlin
In my case I need to define a fixed height and I did the following:
val bottomSheet: View? = dialog.findViewById(R.id.design_bottom_sheet)
BottomSheetBehavior.from(bottomSheet!!).peekHeight = 250
this way you also have access to any property of the BottomSheetBehavior such as halfExpandedRatio
I would advise against using ids to find views. In the BottomSheetDialogFragment the dialog is a BottomSheetDialog which exposes the behavior for the bottom sheet. You can use that to set the peek height.
(dialog as BottomSheetDialog).behavior.peekHeight = ...

Create Scene programmatically (ViewGroup with one TextView)

I usually prefer to work with classes instead of XML.
Now this is the ordinary way of creating a scene:
TransitionInflater inflater = TransitionInflater.from(this);
ViewGroup mSceneRoot = (ViewGroup) findViewById(R.id.sceneRoot);
Scene mScene2 = Scene.getSceneForLayout(mSceneRoot, R.layout.transition_event,this);
TransitionManager mTransitionManager = inflater.inflateTransitionManager(R.anim.transitions_mgr, mSceneRoot);
mTransitionManager.transitionTo(mScene2);
Pretty neat. Since the R.layout.transition_event is only a TextView, it creates the following layouts. LinearLayout is the root.
For making things happen programmatically we can use the Scene(ViewGroup sceneRoot, ViewGroup layout) constructor instead of Scene.getSceneForLayout(..).
My problem is the ViewGroup layout parameter. Since I want to have only one textview, if I create a FrameLayout and add the textview this will create an extra view as the above screenshot which is not the same.
I either need something like <merge/> but programmatically or "convert" TextView into a ViewGroup.
Here is my best try so far:
# I try to do the equivalent of .getSceneForLayout() here
ViewGroup vg = new ViewGroup(MainActivity.this) {
#Override
protected void onLayout(boolean b, int i, int i2, int i3, int i4) {
}
};
TextView tv = new TextView(MainActivity.this);
tv.setText("YOLO!");
vg.addView(tv,0);
mScene2 = new Scene(mSceneRoot, vg);
Which btw produces:
No sure if worths the hustle but I want to figure this out.

Android get layout height and width in a fragment

I am working on a fragment and I want to get the dimension of a layout contained in the xml fragment layout.
When I try the code
RelativeLayout myLayout = view.findViewById(R.id.myLayout);
myLayout.getHeight();
it returns 0.
I need these dimensions to put inside myLayout other objects.
I try to use:
myLayout.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener(){
#Override
public void onGlobalLayout() {
mHeight = myLayout.getHeight();
mWidth= myLayout.getWidth();
System.out.println("width: "+mWidth+" height: "+mHeight);
}
});
but this code is invoke a lot of time and I don't know exactly when it is execute.
I need these dimensions into public void onActivityCreated () method. Is it possible?
There's a cleaner solution to this, just use the View.post() method on your fragment's root view, and you can call getMeasuredHeight()/getMeasuredWidth() and get the actual values.
E.g.
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.myfragment, container, false);
root.post(new Runnable() {
#Override
public void run() {
// for instance
int height = root.getMeasuredHeight();
}
});
return root;
}
Very neat and tidy and no messy mucking about with the ViewTreeObserver.
I've only tested this with android-23 devices, but the API has had this method since level 1.
Anyway, WFM.
The addOnGlobalLayoutListener will be called whenever small change of the view happened. So you need to remove this listener from the view.
Simple usage:
public static void removeOnGlobalLayoutListener(View v, ViewTreeObserver.OnGlobalLayoutListener listener){
if (Build.VERSION.SDK_INT < 16) {
v.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
} else {
v.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
}
}
I would suggest you to check :
if (myLayout.getHeight()>0 && myLayout.getWidth()>0) {
// Do some code...
removeOnGlobalLayoutListener(..)
}
In onActivityCreated, the view hasn't been measured yet.
So no, you can't get the measurements from there. onGlobalLayout is a good place to do it. Layouts happen directly after measurement.
You can remove your listener afterwards, if you only want to do it once. Note that layouts can change size though (soft keyboards appearing, for example)

Android ScrollView, scroll before visible

how can I set scroll of scrollview to x pixels, before it's even shown?
In ScrollView I have some Views and i know that it will fill screen. Can I scroll to let say second View, so that first View is not visible when activity is started?
Now I have sth like this, but I think it's not perfect, sometimes, I see first View, and then it's scrolled to the second one
#Override
public void onGlobalLayout() {
if (mHorizontalScrollView.getChildCount() > 0 && mHorizontalScrollView.getChildAt(0).getWidth() > mScreenWidth) {
hsv.scrollTo(100, 0);
}
}
EDIT!!
Second attempt was to use http://developer.android.com/reference/android/view/ViewTreeObserver.OnPreDrawListener.html instead of http://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html
In OnPreDrawListener we can read that At this point, all views in the tree have been measured and given a frame. Clients can use this to adjust their scroll bounds or even to request a new layout before drawing occurs. so basically at this point we should adjust scrolling. So I created:
#Override
public boolean onPreDraw() {
if (hsv.getChildCount() > 0 && hsv.getChildAt(0).getWidth() > mScreenWidth) {
hsv.scrollTo(100, 0);
return false;
}
return true;
}
but now it's never working for me.
I combined onGlobalLayout with code below. It's not so great to use that hack but it still quite efficient. When I get onGlobalLayout event I check if layouts are done and then if it's ok I use method below.
// hsv - horizontal scroll view
private void forceShowColumn(final int column) {
int scrollTo = childViewWidth * column;
if (scrollTo == hsv.getScrollX()) {
return;
}
hsv.scrollTo(scrollTo, 0);
hsv.postDelayed(new Runnable() {
#Override
public void run() {
forceShowColumn(column);
}
}, 10);
}
try View.post(Runnable) in onCreate-method.
I solved this issue by implementing View.OnLayoutChangeListener in the fragment that controls my ScrollView.
public class YourFragment extends Fragment implements View.OnLayoutChangeListener{
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.your_fragment_layout, container, false);
//set scrollview layout change listener to be handled in this fragment
sv = (ScrollView) view.findViewById(R.id.your_scroll_view);
sv.addOnLayoutChangeListener(this);
return view;
}
...
public void onLayoutChange (View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom){
switch (v.getId())
{
case R.id.your_scroll_view:
{
sv.scrollTo(0, sv.getTop());
}
}
}
The correct way to do this, is to call scrollTo() on the ScrollView after the view has been through its measurement and layout passes, otherwise the width of the content in the scrollView will be 0, and thus scrollTo() will not scroll to the right position. Usually after the constructor has been called and after the view has been added to its parent.
See http://developer.android.com/guide/topics/ui/how-android-draws.html for more insight on how android draws views.
MrJre gives the most elegant solution: "override onLayout() in the scrollview and do it there after super.onLayout()"
Example code here:
https://stackoverflow.com/a/10209457/1310343
Use :
scrollTo (int x, int y)
It sets the scrolled position of your view. This will cause a call to onScrollChanged
For more details : see this
ScrollView ScrollTo

Categories

Resources