o9s
is a microblog
home archives search feed blogroll


Animate Search Bars Up The Screen

I have screens in my apps that only exist for the purpose of searching. I wanted to center the search bars vertically as a way of making it obvious to my users that they need to input a query. I also needed to move the search bars up to leave space to display the result rows.

Android

Android Animation

<!-- Dummy item to prevent search_edit_text from receiving focus -->
<LinearLayout
  android:focusable="true"
  android:focusableInTouchMode="true"
  android:layout_width="0px"
  android:layout_height="0px"/>

<EditText
  android:id="@+id/search_edit_text"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:drawableLeft="@drawable/ic_search"
  android:layout_centerVertical="true" />

A dummy item is used to catch focus before the search input does. This is because I use the OnFocusChangeListener to trigger the translation animation. I want the event to be triggered by the user.

I used the instruction android:layout_centerVertical="true" to center the search input vertically on my screen. This instruction cannot be used in a LinearLayout, it has to be used in a RelativeLayout, therefore make sure the parent view of your EditText control is a RelativeLayout.

EditText searchEditText = (EditText) findViewById(R.id.search_edit_text);
searchEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
  @Override
  public void onFocusChange(View view, boolean b) {
    ObjectAnimator animation = ObjectAnimator.ofFloat(view, "y", 0f);
    animation.setDuration(500);
    animation.start();
  }
});

ObjectAnimator is a life saver for this kind of animation.

iOS

iOS Animation

self.searchBarTopConstraint.constant = 0;

[UIView animateWithDuration:0.5 animations:^(void) {
    [self.view layoutIfNeeded];
}];

searchBarTopConstraint is an Align Top to: Safe Area” constraint with an initial value of 200. An outlet is created from Interface Builder to the view controller.

Be careful, the function that needs to be called in the animation block is layoutIfNeeded, setNeedsLayout does not work. There’s a whole thread on Stack Overflow about a programmer who made this mistake.

Posted on 2018-03-07   #android     #java     #ios     #objc  






← Next post    ·    Previous post →