I want to animate View right after it was added to parent (something like DrawerLayout). The problem is that View has varying size, and animation target position depends on that size. Simplified sample code:
AnimatingView extends View {
public int offsetX;
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int screenWidth = MeasureSpec.getSize(widthMeasureSpec);
final int screenHeight = MeasureSpec.getSize(heightMeasureSpec);
offsetX = calculateOffset(screenWidth);
...
}
}
Code similar to this triggers the animation:
#Override
public void onClick(View v) {
AnimatingView animatingView = new AnimatingView(getContext());
parentLayout.addView(animatingView);
animatingView.animate().x(animatingView.offsetX).setDuration(500).start();
}
In this case onMeasure() happens after animate(), so animation fails. What is the correct way of doing stuff which depends on view measuring?
The simple & stupid way would be something like animateOnceAfterMeasuring() based on isInitialized flag, but I don't think it the correct way of doing this.
this should work:
AnimatingView animatingView = new AnimatingView(getContext());
parentLayout.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
#Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
v.removeOnLayoutChangeListener(this);
animatingView.animate().x(animatingView.offsetX).setDuration(500).start();
}
});
You can use the ViewTreeObserver for this
#Override
public void onClick(View v) {
final AnimatingView animatingView = new AnimatingView(getContext());
parentLayout.addView(animatingView);
animatingView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < 16) {
animatingView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
animatingView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
animatingView.animate().x(animatingView.offsetX).setDuration(500).start();
}
});
}
Related
I have a BindingAdapter like
#BindingAdapter({ "onGlobalLayout" })
public static void setOnGlobalLayout(View view, ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener) {
ViewTreeObserver vto = view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(onGlobalLayoutListener);
}
In XML I have a View like
<View
android:id="#+id/viewId"
bind:onGlobalLayout="#{viewModel.onLayoutListener}"
/>
In ViewModel I have
public ViewTreeObserver.OnGlobalLayoutListener onLayoutListener(View view){
return new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// get x,y,width, height of view
}
};
}
Now I want to send the current View to ViewModel so I add a parametter View view to onLayoutListener but in XML I don't know how to send it.
Any help or suggestion would be great appreciated
UPDATE
Thank #pskink for suggest a better way for checking layout change.
With android:onLayoutChange I don't need BindingAdapter
<View
android:id="#+id/viewId"
android:onLayoutChange="#{viewModel.onLayoutListener(viewId)}"
/>
Java
public View.OnLayoutChangeListener onLayoutUpdateWeightSuccessfulListener(final View v) {
return new View.OnLayoutChangeListener() {
#Override
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
// left, top
}
};
}
simply pass your View id, it should work
bind:onGlobalLayout="#{viewModel.onLayoutListener(viewId)}"
I am using recylerview in my application and whenever new element is added to recyclerview, it scrolls to last element by using
recyclerView.scrollToPosition(adapter.getCount());
But, whenever keyboard opens(because of editTextView), it resizes the view and recyclerview gets smaller, but couldn't scroll to last element.
android:windowSoftInputMode="adjustResize"
I even tried to used the following code to scroll to last element, but it didn't work
editTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
recyclerView.scrollToPosition(chatAdapter.getItemCount());
}
}
});
I can try adjustPan to shift the pan up, but it is hiding my toolbar.
Please suggest any way to rectify the issue.
You can catch keyboard up changes using recyclerview.addOnLayoutChangeListener().
If bottom is smaller than oldBottom then keyboard is in up state.
if ( bottom < oldBottom) {
recyclerview.postDelayed(new Runnable() {
#Override
public void run() {
recyclerview.smoothScrollToPosition(bottomPosition);
}
}, 100);
}
Add this your activity or fragment:
if (Build.VERSION.SDK_INT >= 11) {
recyclerView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
#Override
public void onLayoutChange(View v,
int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
if (bottom < oldBottom) {
recyclerView.postDelayed(new Runnable() {
#Override
public void run() {
recyclerView.smoothScrollToPosition(
recyclerView.getAdapter().getItemCount() - 1);
}
}, 100);
}
}
});
}
It works for me
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
I found the postDelayed to be unnecessary and using adapter positions doesn't account for when the recycler is scrolled to somewhere in the middle of an item. I achieved the look I wanted with this:
recycler.addOnLayoutChangeListener((view, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
if (bottom < oldBottom) {
messageRecycler.scrollBy(0, oldBottom - bottom);
}
})
Although this an old question, I experienced this problem today and I found out that none of of the above method works. This is my solution
recyclerView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
#Override
public void onLayoutChange(View v,
int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
if (bottom < oldBottom) {
final int lastAdapterItem = mAdapter.getItemCount() - 1;
recyclerView.post(new Runnable() {
#Override
public void run() {
int recyclerViewPositionOffset = -1000000;
View bottomView = linearLayoutManager.findViewByPosition(lastAdapterItem);
if (bottomView != null) {
recyclerViewPositionOffset = 0 - bottomView.getHeight();
}
linearLayoutManager.scrollToPositionWithOffset(lastAdapterItem, recyclerViewPositionOffset);
}
});
}
});
}
This works.
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private LinearLayoutManager mManager;
...
mManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mManager);
(initialize and set adapter.)
mRecyclerView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
#Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
if (bottom < oldBottom) scrollToBottom();
}
});
private void scrollToBottom() {
mManager.smoothScrollToPosition(mRecyclerView, null, mAdapter.getItemCount());
}
recyclerView.smoothScrollToPosition(recyclerView.getAdapter().getItemCount());
It works properly in support library version 27.0.1
There is nothing to set in the manifest.
val currentScrollPosition = 0
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
currentScrollPosition = recyclerView.computeVerticalScrollOffset() + recyclerView.computeVerticalScrollExtent()
}
override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) { }
})
storyList.addOnLayoutChangeListener { view, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
if (bottom < oldBottom) {
if (currentScrollPosition >= recyclerView.computeVerticalScrollRange()) {
recyclerVIew.post {
recyclerView.overScrollMode = RecyclerView.OVER_SCROLL_NEVER
recyclerView.smoothScrollBy(0, recyclerView.computeVerticalScrollRange() - recyclerView.computeVerticalScrollOffset() + recyclerView.computeVerticalScrollExtent())
}
}
} else {
recyclerView.overScrollMode = RecyclerView.OVER_SCROLL_ALWAYS
}
}
layoutManager.scrollToPositionWithOffset(chatMessageAdapter.getItemCount() - 1, 0);
You can use addOnItemTouchListener to see the scrolling change:
private Boolean scrollListerActivate = true;
mRecyclerViewTop.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if(scrollListerActivate == true) {
scrollListTopManager();
}
}
});
To scroll for last (or other) position you should use scrollListTopManager method:
public void scrollListTopManager() {
int position = 0;
int itemCount = mRecyclerViewTop.getAdapter().getItemCount();
position = itemCount - 1;
mRecyclerViewTop.scrollToPosition(position);
}
You should also use addOnItemTouchListener to stop using scrollListTopManager method, if you want to scroll manually:
mRecyclerViewTop.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent
motionEvent) {
scrollListerActivate = false;
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent)
{}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean b) {}
});
When you open chat you will get last message at the end of recycle view:
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
Below code will make adjustments according to keyboard!
recyclerView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
#Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
if ( bottom <= oldBottom) {
recyclerview.postDelayed(new Runnable() {
#Override
public void run() {
recyclerview.smoothScrollToPosition(bottom);
}
}, 100);
}
}
});
Bind the RecyclerView inside NestedScrollView
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.support.v4.widget.NestedScrollView>
I have a button in my layout. And I am animating the position of that button using ObjectAnimator with translationX animation.
ObjectAnimator btnAnimator = ObjectAnimator.ofFloat(myBtn, "translationX",
ViewHelper.getTranslationX(myBtn), 0);
btnAnimator.addListener(new AnimatorListener() {
#Override
public void onAnimationCancel(Animator arg0) {}
#Override
public void onAnimationEnd(Animator arg0) {
Log.i("TAG","Animation Finished");
}
#Override
public void onAnimationRepeat(Animator arg0) {}
#Override
public void onAnimationStart(Animator arg0) {}
});
btnAnimator.setDuration(animationSpeed).start();
Now I would like to have a listener for the TranslationX of that button to notify whenever the TranslationX position of the button changes.
Here's an easy way I found to do what you're after:
btnAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
Log.e("TAG", "translateX: "+animation.getAnimatedValue("translationX"));
}
});
btnAnimator.setDuration(animationSpeed).start();
Two possible approaches:
1) Override onLayout() in your view to manually compare and detect position changes.
2) Use onLayoutChangeListener on your View:
button.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) {
// Check your new position vs the old one
}
});
I used this and it worked as a decent way of listening for changes of the view translation.
var previousTranslationX = view.translationX
var previousTranslationY = view.translationY
view.viewTreeObserver.addOnDrawListener {
if (previousTranslationX != view.translationX ||
previousTranslationY != view.translationY) {
previousTranslationX = view.translationX
previousTranslationY = view.translationY
dispatchViewTranslationUpdated(view)
}
}
Simply register a callback to be invoked when the view tree is about to be drawn.
Note: This listener almost called every time the view is drawn!
public class MyView extends View {
private float oldScaleX;
public MyView(Context context) {
super(context);
getViewTreeObserver().addOnDrawListener(new ViewTreeObserver.OnDrawListener() {
#Override
public void onDraw() {
// Many things can invoke this method! We don't know why view going
// to be redrawn, So we must determine the cause ourselves.
float newScaleX=getScaleX();
if (oldScaleX!=newScaleX) {
scaleXUpdated();
oldScaleX=newScaleX;
}
}
});
}
private void scaleXUpdated() {
Log.e(TAG,"scaleX updated "+getScaleX);
}
}
In the view hierarchy:
Window > ViewGroup (root) > ViewGroup[...] > View (child)
I need to know root dimension in a profound child onMeasure event.
Exemple:
#Override
protected void onMeasure(int wMS, int hMS) {
int desiredW = Math.round(rootW * factorW);
int desiredH = Math.round(rootH * factorH);
/* ... compute final dimensions ... */
setMeasuredDimension(finalW, finalH);
}
Note: At this moment, getRootView and getWindow dimentions equals to 0 because children have to setMeasuredDimention before their parents
Considering a lot of children needing this dimension, to do it:
I created an interface:
public interface OnRootSizeChanged {
public void onRootSizeChanged(int w, int h);
}
I implemented my child which now implements OnRootSizeChanged inteface:
private int rootW;
private int rootH;
#Override
public void onRootSizeChanged(int w, int h) {
rootW = w;
rootH = h;
}
I implemented root view:
#Override
protected void onMeasure(int wMS, int hMS) {
int w = MeasureSpec.getSize(wMS);
int h = MeasureSpec.getSize(hMS);
dispatchOnRootSizeChange(this, w, h);
super.onMeasure(wMS, hMS);
}
private void dispatchOnRootSizeChange(ViewGroup v, int w, int h) {
for (int i = 0, n = v.getChildCount(); i < n; i++) {
View child = v.getChildAt(i);
if (child instanceof OnRootSizeChanged)
((OnRootSizeChanged) child).onRootSizeChanged(w, h);
if (child instanceof ViewGroup)
dispatchOnRootSizeChange((ViewGroup) child, w, h);
}
}
My question is:
Have I simpler way to do this without recursivity or with better practice ?
Update: This method is invalid in case of ViewPager element in ViewGroup[...] breabcrumb. When ViewPager instantiate children pages, they have not yet received OnRootSizeChanged event so:
Children have to ask the root dimension, no the root to tell his dimension to their children
So I searched how to target root from a profound child to ask him:
getRootView() not seems targeting the view attached with setContentView()
getWindow().getDecorView() either
One possible way is:
On child:
#Override
protected void onMeasure(int wMS, int hMS) {
ViewParent parent = getParent();
while (parent instanceof RootViewClass == false)
parent = parent.getParent();
RootViewClass root = (RootViewClass) parent;
int desiredW = Math.round(root.w * factorW);
int desiredH = Math.round(root.h * factorH);
/* ... compute final dimensions ... */
setMeasuredDimension(finalW, finalH);
}
On root instance of RootViewClass:
public int w, h;
#Override
protected void onMeasure(int wMS, int hMS) {
w = MeasureSpec.getSize(wMS);
h = MeasureSpec.getSize(hMS);
super.onMeasure(wMS, hMS);
}
But with lot of children, I don't think this is a good practice. If I could find root view without use of loop.
You can forward the parent's size by storing those values in the onMeasure() method as you receive them and then letting the children access the values in their onMeasure() method through the Context reference:
// simple interface
public interface ParentRef {
void YourViewGroup getRoot();
}
// the Activity implements the interface above
public class YourActivity extends Activity implements ParentRef {
private YourViewGroup mRoot;
//in onCreate initialize the mRoot reference
#Override
public YourViewGroup getRoot() {
return mRoot;
}
//... rest of the Activity
}
// the custom ViewGroup will store the dimensions:
//fields in the root view
private int mCurWidth;
private int mCurHeight;
#Override
protected void onMeasure(int wMS, int hMS) {
int w = MeasureSpec.getSize(wMS);
int h = MeasureSpec.getSize(hMS);
mCurWidth = w;
mCurHeight = h;
// now as the children are measured they can see the values above
super.onMeasure(wMS, hMS);
}
public int getStoredWidth() {
return mCurWidth;
}
public int getStoredHeight() {
return mCurHeight;
}
// in the children's onMeasure simply do:
#Override
protected void onMeasure(int wMS, int hMS) {
final YourViewGroup root = ((ParentRef) getContext()).getRoot();
//width root.getStoredWidth()
// height root.getStoredHeight()
/* ... compute final dimensions ... */
setMeasuredDimension(finalW, finalH);
}
You can use a ViewTreeObserver (http://developer.android.com/reference/android/view/ViewTreeObserver.html)
//...get your view, than attach a viewTreeObserver on it!
ViewTreeObserver vto = view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
//misure the view here, like view.getHeight()
}
});
I want animation like expanding of the photos when I click folder of photos at gallery, like in this video about Android gallery.
i have two views in same custom viewgroup
view1 is in 0,0
view2 is in 100,100
since click "start" view1 will move to 100,0 and view2 will move to 0,100
My solution so far:
I use timer for refresh layout with new position by requestlayout.
the views' position will refresh by onLayout:
It works but it's not a native function and it is very slow with 100 views moving at same time.
Full code:
private class MyViewGroup extends ViewGroup{
View view1,view2;
Button btn;
public MyViewGroup(Context context) {
super(context);
view1=new View(context);
view1.setBackgroundColor(Color.RED);
this.addView(view1);
view2=new View(context);
view2.setBackgroundColor(Color.BLUE);
this.addView(view2);
btn=new Button(context);
btn.setText("start");
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
xLayout=0;
handler.sendEmptyMessage(0);
}
});
this.addView(btn);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int w = MeasureSpec.getSize(widthMeasureSpec);
int h= MeasureSpec.getSize(heightMeasureSpec);
int widthSpec = MeasureSpec.makeMeasureSpec(50, MeasureSpec.EXACTLY);
int heightSpec = MeasureSpec.makeMeasureSpec(50, MeasureSpec.EXACTLY);
view1.measure(widthSpec,heightSpec);
view2.measure(widthSpec,heightSpec);
btn.measure(widthSpec,heightSpec);
this.setMeasuredDimension(w, h);
}
private int xLayout=0;
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
view1.layout(xLayout,0,xLayout+50,50);
view2.layout(100-xLayout,100,150-xLayout,150);
btn.layout(0,200,50,250);
}
private void startAnimation(){
Timer timer = new Timer() ;
timer.schedule(new TimerTask(){
#Override
public void run() {
if(xLayout<100){
handler.sendEmptyMessage(0);
}
this.cancel();
}
},5);
}
private Handler handler=new Handler(){
#Override
public void handleMessage(Message msg) {
xLayout=xLayout+20;
view1.requestLayout();
startAnimation();
}
} ;
}
http://android-developers.blogspot.fr/2011/05/introducing-viewpropertyanimator.html
myView.animate().x(500).y(500);
we can use "LayoutTransition" as
final LayoutTransition transitioner = new LayoutTransition();
myViewGroup.setLayoutTransition(transitioner);
and when we click "start" addview
full code
private class MyViewGroup extends ViewGroup{
View view1,view2;
Button btn;
public MyViewGroup(final Context context) {
super(context);
view1=new View(context);
view1.setBackgroundColor(Color.RED);
this.addView(view1);
view2=new View(context);
view2.setBackgroundColor(Color.BLUE);
this.addView(view2);
btn=new Button(context);
btn.setText("start");
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
xLayout+=100;
MyViewGroup.this.addView(new View(context));
}
});
this.addView(btn);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int w = MeasureSpec.getSize(widthMeasureSpec);
int h= MeasureSpec.getSize(heightMeasureSpec);
int widthSpec = MeasureSpec.makeMeasureSpec(50, MeasureSpec.EXACTLY);
int heightSpec = MeasureSpec.makeMeasureSpec(50, MeasureSpec.EXACTLY);
view1.measure(widthSpec,heightSpec);
view2.measure(widthSpec,heightSpec);
btn.measure(widthSpec,heightSpec);
this.setMeasuredDimension(w, h);
}
private int xLayout=0;
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
view1.layout(xLayout,0,xLayout+50,50);
view2.layout(100-xLayout,100,150-xLayout,150);
btn.layout(0,200,50,250);
}
}