**All of the information below is with regards to the icons illustrated on the right side of the gif.
I have created a simple toolbar that has a button that changes the image based on the position of the fragment. Everything works fine, however, I can't seem to get the fading correctly. I want the images to fade nicely as the fragment changes. Right now, going from the center (position 1) to the left (position 0) has a nice fade. The icon changes from an equalizer to a chat icon. However, going back from left (position 0) to center (position 1) makes the image pop into frame (not a fade). Additionally the same is observed going from center (position 1) to the right (position 2) and vice versa. There is no fading in this case either.
I believe the issue is with the if else statements and the setAlpha.
Position 0 (Left side)
Position 1 (Center)
Position 2 (Right side)
Gif Demo (What current code does):
https://imgur.com/a/vNEJZAJ
Code:
public class TopVariableFunctionalityButtonView extends FrameLayout implements ViewPager.OnPageChangeListener {
// Initialize content
private ImageView mVariableFunctionalityButtonImageView;
private ImageView mVariableFunctionalityButtonBackgroundImageView;
private ArgbEvaluator mArgbEvaluator;
// Initialize color change
private int mCenterVariableFunctionalityButtonColor;
private int mSideVariableFunctionalityButtonColor;
private int mCenterVariableFunctionalityButtonBackgroundColor;
private int mSideVariableFunctionalityButtonBackgroundColor;
public TopVariableFunctionalityButtonView(#NonNull Context context) {
this(context, null);
}
public TopVariableFunctionalityButtonView(#NonNull Context context, #Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public TopVariableFunctionalityButtonView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void setUpWithViewPager(ViewPager viewPager) {
viewPager.addOnPageChangeListener(this);
mVariableFunctionalityButtonImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (viewPager.getCurrentItem() == 2)
HomeActivity.openSettings(getContext());
}
});
}
private void init() {
LayoutInflater.from(getContext()).inflate(R.layout.view_top_variable_functionality_button, this, true);
// Initialize top variable functionality button image
mVariableFunctionalityButtonImageView = findViewById(R.id.view_top_variable_functionality_button_image_view);
// Initialize top variable functionality button image background
mVariableFunctionalityButtonBackgroundImageView = findViewById(R.id.view_top_variable_functionality_button_background_image_view);
// Set start color and end color for button icons
mCenterVariableFunctionalityButtonColor = ContextCompat.getColor(getContext(), R.color.white);
mSideVariableFunctionalityButtonColor = ContextCompat.getColor(getContext(), R.color.iconColor);
mCenterVariableFunctionalityButtonBackgroundColor = ContextCompat.getColor(getContext(), R.color.transparentSearch);
mSideVariableFunctionalityButtonBackgroundColor = ContextCompat.getColor(getContext(), R.color.secondaryColor);
// Evaluate the difference between colors
mArgbEvaluator = new ArgbEvaluator();
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == 0) {
// Change color of icons based on view
setColor(1 - positionOffset);
// Change variable button image
mVariableFunctionalityButtonImageView.setAlpha(1 - positionOffset);
mVariableFunctionalityButtonImageView.setBackgroundResource(R.drawable.ic_chat);
} else if (position == 1) {
// Change color of icons based on view
setColor(positionOffset + 1);
// Change variable button image
mVariableFunctionalityButtonImageView.setAlpha(positionOffset + 1);
mVariableFunctionalityButtonImageView.setBackgroundResource(R.drawable.ic_equalizer);
} else if (position == 2) {
// Change color of icons based on view
setColor(positionOffset + 1);
// Change variable button image
mVariableFunctionalityButtonImageView.setAlpha(positionOffset + 1);
mVariableFunctionalityButtonImageView.setBackgroundResource(R.drawable.ic_settings);
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
private void setColor(float fractionFromCenter) {
int variableFunctionalityButtonColor = (int) mArgbEvaluator.evaluate(fractionFromCenter,
mCenterVariableFunctionalityButtonColor, mSideVariableFunctionalityButtonColor);
int variableFunctionalityButtonBackgroundColor = (int) mArgbEvaluator.evaluate(fractionFromCenter,
mCenterVariableFunctionalityButtonBackgroundColor, mSideVariableFunctionalityButtonBackgroundColor);
mVariableFunctionalityButtonImageView.setColorFilter(variableFunctionalityButtonColor);
mVariableFunctionalityButtonBackgroundImageView.setColorFilter(variableFunctionalityButtonBackgroundColor);
}
}
Related
I have fragment from which I'm launching activity with shared element transition that has viewpager in it, the enter transition works fine but when i scroll in view pager and finish transition the shared image comes from left side which is not desired it should reposition itself to where it was launched, here is my code:
Intent myIntent = new Intent(getActivity(), EnlargeActivity.class);
ActivityOptionsCompat options = ActivityOptionsCompat.
makeSceneTransitionAnimation(getActivity(),
imageView,
ViewCompat.getTransitionName(imageView));
startActivity(myIntent, options.toBundle());
I'm updating view and its name in activity that contains viewpager when finishing activity, but its going with blink:
public void finishAfterTransition() {
setEnterSharedElementCallback(new SharedElementCallback() {
#Override
public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
// Clear all current shared views and names
names.clear();
sharedElements.clear();
ViewGroup viewGroup = (ViewGroup) viewPagerDetail.getAdapter()
.instantiateItem(viewPagerDetail, viewPagerDetail.getCurrentItem());
if (viewGroup == null) {
return;
}
// Map the first shared element name to the child ImageView.
sharedElements.put(viewGroup.findViewById(R.id.img).getTransitionName(), viewGroup.findViewById(R.id.img));
// setExitSharedElementCallback((SharedElementCallback) this);
}
});
super.finishAfterTransition();
Basically, Android start the transition with your pre-defined View and transitionName and automatically use the same properties for the return transition. When you change your focused View in ViewPager, Android doesn't know about that and keep the transition on the previous one on its way back. So you need to inform Android about the changes:
Remap the transition properties: Use setEnterSharedElementCallback to change the transitionName and View to the new one before returning from Activity2.
Wait for the Activity1 to finish rendering addOnPreDrawListener.
It's a bit complex in the final implementation. But you can look at my sample code https://github.com/tamhuynhit/PhotoGallery. I try to implement the shared-element-transition from many simple to complex sections.
Your problem appeared from Level 3 and solved in Level 4.
I am writing a tutorial about this but it's not in English so hope the code can help
UPDATE 1: Work flow
Here is how I implement it in my code:
Override finishAfterTransition in Activity2 and call setEnterSharedElementCallback method to re-map the current selected item in ViewPager. Also, call setResult to pass the new selected index back to previous activity here.
#Override
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void finishAfterTransition() {
setEnterSharedElementCallback(new SharedElementCallback() {
#Override
public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
View selectedView = getSelectedView();
if (selectedView == null)
return;
// Clear all current shared views and names
names.clear();
sharedElements.clear();
// Store new selected view and name
String transitionName = ViewCompat.getTransitionName(selectedView);
names.add(transitionName);
sharedElements.put(transitionName, selectedView);
setExitSharedElementCallback((SharedElementCallback) null);
}
});
Intent intent = new Intent();
intent.putExtra(PHOTO_FOCUSED_INDEX, mCurrentIndex);
setResult(RESULT_PHOTO_CLOSED, intent);
super.finishAfterTransition();
}
Write a custom ShareElementCallback so I can set the callback before knowing which View is going to be used.
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static class CustomSharedElementCallback extends SharedElementCallback {
private View mView;
/**
* Set the transtion View to the callback, this should be called before starting the transition so the View is not null
*/
public void setView(View view) {
mView = view;
}
#Override
public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
// Clear all current shared views and names
names.clear();
sharedElements.clear();
// Store new selected view and name
String transitionName = ViewCompat.getTransitionName(mView);
names.add(transitionName);
sharedElements.put(transitionName, mView);
}
}
Override onActivityReenter in Activity1, get the selected index from the result Intent. Set setExitSharedElementCallback to re-map new selected View when the transition begins.Call supportPostponeEnterTransition to delay a bit because your new View may not be rendered at this point. Use getViewTreeObserver().addOnPreDrawListener to listen for the layout changes, find the right View by the selected index and continue the transition supportStartPostponedEnterTransition.
#Override
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void onActivityReenter(int resultCode, Intent data) {
if (resultCode != LevelFourFullPhotoActivity.RESULT_PHOTO_CLOSED || data == null)
return;
final int selectedIndex = data.getIntExtra(LevelFourFullPhotoActivity.PHOTO_FOCUSED_INDEX, -1);
if (selectedIndex == -1)
return;
// Scroll to the new selected view in case it's not currently visible on the screen
mPhotoList.scrollToPosition(selectedIndex);
final CustomSharedElementCallback callback = new CustomSharedElementCallback();
getActivity().setExitSharedElementCallback(callback);
// Listen for the transition end and clear all registered callback
getActivity().getWindow().getSharedElementExitTransition().addListener(new Transition.TransitionListener() {
#Override
public void onTransitionStart(Transition transition) {}
#Override
public void onTransitionPause(Transition transition) {}
#Override
public void onTransitionResume(Transition transition) {}
#Override
public void onTransitionEnd(Transition transition) {
removeCallback();
}
#Override
public void onTransitionCancel(Transition transition) {
removeCallback();
}
private void removeCallback() {
if (getActivity() != null) {
getActivity().getWindow().getSharedElementExitTransition().removeListener(this);
getActivity().setExitSharedElementCallback((SharedElementCallback) null);
}
}
});
// Pause transition until the selected view is fully drawn
getActivity().supportPostponeEnterTransition();
// Listen for the RecyclerView pre draw to make sure the selected view is visible,
// and findViewHolderForAdapterPosition will return a non null ViewHolder
mPhotoList.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
mPhotoList.getViewTreeObserver().removeOnPreDrawListener(this);
RecyclerView.ViewHolder holder = mPhotoList.findViewHolderForAdapterPosition(selectedIndex);
if (holder instanceof ViewHolder) {
callback.setView(((ViewHolder) holder).mPhotoImg);
}
// Continue the transition
getActivity().supportStartPostponedEnterTransition();
return true;
}
});
}
UPDATE 2: getSelectedItem
To get selected View from the ViewPager, don't use getChildAt or you get the wrong View, use findViewWithTag instead
In the PagerAdapter.instantiateItem, use position as tag for each View:
#Override
public View instantiateItem(ViewGroup container, int position) {
// Create the View
view.setTag(position)
// ...
}
Listen to onPageSelected event to get the selected index:
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mSelectedIndex = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Call getSelectedView to get the current view by the selected index
private View getSelectedView() {
try {
return mPhotoViewPager.findViewWithTag(mSelectedIndex);
} catch (IndexOutOfBoundsException | NullPointerException ex) {
return null;
}
}
This is actually a default behavior, I was struggling SharedElementTransitions a lot, but I have nested fragments. I got my solution from an article (very recent article), it shows an implementation with a RecyclerView, which I assume you have. In short, the solution is to override onLayoutChange :
recyclerView.addOnLayoutChangeListener(
new OnLayoutChangeListener() {
#Override
public void onLayoutChange(View view,
int left,
int top,
int right,
int bottom,
int oldLeft,
int oldTop,
int oldRight,
int oldBottom) {
recyclerView.removeOnLayoutChangeListener(this);
final RecyclerView.LayoutManager layoutManager =
recyclerView.getLayoutManager();
View viewAtPosition =
layoutManager.findViewByPosition(MainActivity.currentPosition);
// Scroll to position if the view for the current position is null (not
// currently part of layout manager children), or it's not completely
// visible.
if (viewAtPosition == null
|| layoutManager.isViewPartiallyVisible(viewAtPosition, false, true)){
recyclerView.post(()
-> layoutManager.scrollToPosition(MainActivity.currentPosition));
}
}
});
Here is the article, and you will also find the project on GitHub.
I have a RelativeLayout that contains many child views with various touch events. I want to get notified when the user swipes anywhere on the parent RelativeLayout so I can update some UI while still letting the child views handle their own touch/drag events. What is the standard way of accomplishing this for Android?
I was thinking that I could put an overlay over all the views and have it detect swipe gestures and if it wasn't a swipe I could pass the touch event on to other views in the hierarchy. It doesn't seem like Android supports that sort of touch detection and once one view decides to see if a event is a certain gesture no other views will be able to see the events.
A swipe gesture consists of three touch events: ACTION_DOWN, ACTION_MOVE and ACTION_UP. You need to record all three events and then see if it was a swipe or not. If it was not a swipe then we would need to pass those events to other child views to see if it meets their criteria for the gesture they are looking for. If it is a swipe we would want to block the events from being sent to the child view. Just not sure if this is actually possible.
Update
Using the ideas of the users in the answers section I was able to write a layout that met my specification. This RelativeLayout just handles right and left swipes but could be added to to handle more directions. OnSwipeListener is just an interface with two methods void swipedLeft() and void swipedRight().
public class SwipeRelativeLayout extends RelativeLayout {
public OnSwipeListener mSwipeListener = null;
private static final int SWIPE_DISTANCE_THRESHOLD = 100;
private float mStartX = 0;
private float mStartY = 0;
private float mEndX = 0;
private float mEndY = 0;
public SwipeRelativeLayout(Context context) {
super(context);
}
public SwipeRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SwipeRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public SwipeRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean handled = onTouchEvent(event);
if (event.getAction() == MotionEvent.ACTION_UP) return handled;
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
mStartX = event.getRawX();
mStartY = event.getRawY();
break;
}
case MotionEvent.ACTION_MOVE: {
float distanceX = event.getRawX() - mStartX;
float distanceY = event.getRawY() - mStartY;
if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD) {
if (distanceX > 0) {
if (mSwipeListener != null) mSwipeListener.swipedRight();
} else {
if (mSwipeListener != null) mSwipeListener.swipedLeft();
}
return true;
}
return false;
}
}
return true;
}
}
When a touch event occurs it is first passed to the parent layout view and passed on to child view via onInterceptTouchEvent returning true or false. You want to override and intercept the touch events on the parent RelativeLayout and determine if you have seen a swipe gesture or not. If you have seen a swipe you want to return that you have handled it. In this case ACTION_UP is the end of a possible swipe and if your onTouchEvent handled the event then you can return true and the views below it will not get the finishing event and thus ignore their gestures.
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean handled = onTouchEvent(event);
if (event.getAction() == MotionEvent.ACTION_UP) return handled;
return false;
}
I have a RecyclerView with Expandable Child Views, when the child ViewGroup is clicked it inflates an amount of views animating the ViewGroup height from 0 to the measured viewgroup height, like the following gif:
The problem is: I'm calling smoothScrollToPosition on recyclerView, it smooth scroll to the view position, but it considers the current view height, which is still not expanded, in the above gif i'm touching on the under view of the recyclerview, which dont scroll to position because the view is already visible, but when i touch again (calling the smoothscrolltoposition again) it scroll the view to the correct position, because the view is already expanded.
Is there any approach to scroll the view to the top of screen or just scroll to make content visible?
For references:
This is the method called to inflate the views:
collapsible_content.removeAllViews();
for(int i = 0; i < 5; i++) {
View link_view = getLayoutInflater().inflate(R.layout.list_item_timeline_step_link, collapsible_content, false);
TextView text = (TextView) link_view.findViewById(R.id.step_link_text);
text.setText("Test");
collapsible_content.addView(link_view);
}
And this is my method to expand:
public void toggle() {
collapsible_content.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
Animation a;
if (mExpanded) {
a = new ExpandAnimation(collapsible_content.getLayoutParams().height, 0);
} else {
a = new ExpandAnimation(collapsible_content.getLayoutParams().height, getMeasuredHeight());
}
a.setDuration(mAnimationDuration);
collapsible_content.startAnimation(a);
mExpanded = !mExpanded;
}
And the animation:
private class ExpandAnimation extends Animation {
private final int mStartHeight;
private final int mDeltaHeight;
public ExpandAnimation(int startHeight, int endHeight) {
mStartHeight = startHeight;
mDeltaHeight = endHeight - startHeight;
}
#Override
protected void applyTransformation(float interpolatedTime,
Transformation t) {
final int newHeight = (int) (mStartHeight + mDeltaHeight *
interpolatedTime);
collapsible_content getLayoutParams().height = newHeight;
if (newHeight <= 0) {
collapsible_content setVisibility(View.GONE);
} else {
collapsible_content setVisibility(View.VISIBLE);
}
collapsible_content requestLayout();
}
#Override
public boolean willChangeBounds() {
return true;
}
}
My solution was to constant check for view bottom within applyTransformation method, and compare it with RecyclerView height, if the bottom get higher than the RV height, i scroll by the diff values:
final int bottom = collapsible_content.getBottom();
final int listViewHeight = mRecyclerView.getHeight();
if (bottom > listViewHeight) {
final int top = collapsible_content.getTop();
if (top > 0) {
mRecyclerView.smoothScrollBy(0, Math.min(bottom - listViewHeight + mRecyclerView.getPaddingBottom(), top));
}
}
The trick was to use Math.min to get the view top, so it don't scroll up making the top not visible.
Solution based on ListViewAnimations
Add an animationlistener and start the scrolling of the recyclerview after the expanding animation is finished.
I have a custom Seek bar that that i made following a tutorial on the net. Here is the code for the CustomSeekBar class.
public class CustomSeekBar extends SeekBar {
private ArrayList<ProgressItem> mProgressItemsList;
public CustomSeekBar(Context context) {
super(context);
}
public CustomSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomSeekBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void initData(ArrayList<ProgressItem> progressItemsList) {
this.mProgressItemsList = progressItemsList;
}
#Override
protected synchronized void onMeasure(int widthMeasureSpec,
int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
protected void onDraw(Canvas canvas) {
if (mProgressItemsList.size() > 0) {
int progressBarWidth = getWidth();
int progressBarHeight = getHeight();
int thumboffset = getThumbOffset();
int lastProgressX = 0;
int progressItemWidth, progressItemRight;
for (int i = 0; i < mProgressItemsList.size(); i++) {
ProgressItem progressItem = mProgressItemsList.get(i);
Paint progressPaint = new Paint();
progressPaint.setColor(getResources().getColor(
progressItem.color));
progressItemWidth = (int) (progressItem.progressItemPercentage
* progressBarWidth / 100);
progressItemRight = lastProgressX + progressItemWidth;
// for last item give right to progress item to the width
if (i == mProgressItemsList.size() - 1
&& progressItemRight != progressBarWidth) {
progressItemRight = progressBarWidth;
}
Rect progressRect = new Rect();
progressRect.set(lastProgressX, thumboffset / 2,
progressItemRight, progressBarHeight - thumboffset / 2);
canvas.drawRect(progressRect, progressPaint);
lastProgressX = progressItemRight;
}
super.onDraw(canvas);
}
}
}
I have used this custom widget in a fragment. This fragment has multiple instance of this custom widget.
The fragment is used in multiple activities. There is an activity where the fragment works fine but in another activity where i try to use two of the above fragments i get a NullPointer Exception.
From the stacktrace i can trace the null pointer exception back to the line
if (mProgressItemsList.size() > 0) {
The strange thing is that when i add the fragment to only one framelayout the code works fine. But when i add the fragment to another framelayout in the same activity i get this null pointer exception. I am confused on what is causing this and am wondering what is the best way to tackle this?
The problem was that i was working with the view in the views of my fragment onActivityCreated() method. If you are planning to use the same fragment twice in any activity this is a very bad idea. I had two fragments initialized but only a single fragment and its views was initialized because i was using getActivity().findViewById() .
The solution to this is to work with your fragment's view on onViewCreated(View view, #Nullable Bundle savedInstanceState) and instead of using getActivity().findViewById() using view.findViewById().
I am trying to trigger a click on the Carousel. I want that if I press the forward button, it automatically triggers the click on the carousel and then move forward. The manual click (physical touch) is working but performClick() is not. The code is as follows
//************* Forward Button: Select Objects *************
Button forwardButton = (Button)this.findViewById(R.id.ForwardButton);
forwardButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(NewFieldTrip.this, SelectObjects.class);
//ImagePosition = (int)carousel.getSelectedItemId();
carousel.performClick();
i.putExtra("SelectedScene",ImagePosition);
startActivity(i);
}
});
carousel.setOnItemClickListener(new CarouselAdapter.OnItemClickListener(){
#Override
public void onItemClick(CarouselAdapter<?> parent, View view,
int position, long id) {
Toast.makeText(NewFieldTrip.this, "Select Position=" + position, Toast.LENGTH_SHORT).show();
ImagePosition = position;
}
});
A helping hand would be great :)
EDIT:
public void scrollToChild(int i){
CarouselImageView view = (CarouselImageView)getAdapter().getView(i, null, null);
float angle = view.getCurrentAngle();
if(angle == 0)
return;
if(angle > 180.0f)
angle = 360.0f - angle;
else
angle = -angle;
mFlingRunnable.startUsingDistance(-angle);
}
What type is carousel of? ListView?
So if carousel is ListView then what event are you expected on ListView clicking?
performClick() trigger OnClickListener, which you didn't set to cаrousel. You set OnItemClickListener, so you have to call performItemClick(...). Try it.
UPD:
Try to do folowing:
1) make method Carousel.scrollToChild(int i) public
2)
int itemCount = carousel.getAdapter().getCount();
int item = new Random().nextInt(itemCount);
View view - carousel.getAdapter().getView(item, null, null);
int itemId = carousel.getAdapter().getItemId(item);
carousel.scrollToChild(item);
carousel.performItemClick(view, item, itemId);