How to increase the size of a current focused item

2019-01-13 13:37发布

问题:

I'm trying to make an horizontal list with a RecyclerView, that when I put the focus on an item, increase the size of this. I want to make this effect:

Do you have any ideas to accomplish this?

回答1:

I'm imagining something like this:

  1. Create the horizontal RV
  2. When binding the ViewHolder, attach a FocusChangeListener to the root view of the item
  3. When the item gains focus, scale it to make it slightly bigger; when the focus is lost, revert the animation.

static class ViewHolder extends RecyclerView.ViewHolder {

  public ViewHolder(View root) {
    // bind views
    // ...

    // bind focus listener
    root.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      @Override
        public void onFocusChange(View v, boolean hasFocus) {
          if (hasFocus) {
            // run scale animation and make it bigger
          } else {
            // run scale animation and make it smaller
          }
        }
     });
  }
}


回答2:

Thanks to dextor answer, I could figure out this answer.

I've used the FocusChangeListener and added animation states to change the size of the view:

static class ViewHolder extends RecyclerView.ViewHolder {

public ViewHolder(final View root) {
    // bind views
    // ...

    // bind focus listener
    root.setOnFocusChangeListener(new View.OnFocusChangeListener() {
         @Override
         public void onFocusChange(View v, boolean hasFocus) {
             if (hasFocus) {
                 // run scale animation and make it bigger
                 Animation anim = AnimationUtils.loadAnimation(context, R.anim.scale_in_tv);
                 root.startAnimation(anim);
                 anim.setFillAfter(true);
             } else {
                 // run scale animation and make it smaller
                 Animation anim = AnimationUtils.loadAnimation(context, R.anim.scale_out_tv);
                 root.startAnimation(anim);
                 anim.setFillAfter(true);
             }
         }
    });
}

And the code for the anims:

scale_in_tv:

<scale xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fromXScale="100%"
    android:fromYScale="100%"
    android:toXScale="110%"
    android:toYScale="110%"
    android:pivotX="50%"
    android:pivotY="50%">
</scale>

scale_out_tv:

<scale xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="100"
    android:fromXScale="110%"
    android:fromYScale="110%"
    android:toXScale="100%"
    android:toYScale="100%"
    android:pivotX="50%"
    android:pivotY="50%">
</scale>