property animations animate android android-animation objectanimator

animations - Cómo dar valores de porcentaje en ObjectAnimator en Android



animator android (4)

He hecho esto, pasé demasiado tiempo pero te ahorrará tiempo.

Argumentos:

  1. Ver (Tu vista de soporte)
  2. Ancho de los padres (raíz de su vista)
  3. Ancho del niño (sobre el que desea aplicar la animación)
  4. % (Cuánto porcentaje desea mover su objeto o vista)

No tengas miedo con Argumentos, te lo explico aquí por ejemplo.

Código XML y JAVA :

activity_main.xml :

<LinearLayout android:id="@+id/llProgressParent" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="5dp" android:layout_gravity="center" android:orientation="horizontal" android:weightSum="1" > <View android:id="@+id/viewSuppot" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="0" > </View> <ImageView android:id="@+id/ivProgressChild" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:src="@drawable/ic_launcher" /> </LinearLayout>

MainActivity.java :

private LinearLayout llProgressParent; private View viewSuppot; private ImageView ivProgressChild; private int childWidth, parentWidth; private int percentage = 75;

en onCreate () :

viewSuppot = findViewById(R.id.viewSuppot); llProgressParent = (LinearLayout)findViewById(R.id.llProgressParent); llProgressParent.post(new Runnable() { @Override public void run() { parentWidth = llProgressParent.getMeasuredWidth(); } }); ivProgressChild = (ImageView)findViewById(R.id.ivProgressChild); ivProgressChild.post(new Runnable() { @Override public void run() { childWidth = ivProgressChild.getMeasuredWidth(); } });

Método:

private void animateViewByPercentageOrProgrss(final View view, int parentWidth, int childWidth, int percentage){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } ValueAnimator anim = ValueAnimator.ofInt(view.getMeasuredWidth(), (int) (((float) percentage * parentWidth) / 100)-(childWidth/2)); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { int val = (Integer) valueAnimator.getAnimatedValue(); ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); layoutParams.width = val; view.setLayoutParams(layoutParams); } }); anim.setDuration(2000); anim.start(); }

Cómo llamar al método :

animateViewByPercentageOrProgrss(viewSuppot, parentWidth, childWidth, percentage);

Está Hecho .

Estoy usando objectAnimator para animar un botón de abajo a arriba en Android. Ahora estoy usando el siguiente código

ObjectAnimator transAnimation = ObjectAnimator.ofFloat(button,"translationY",0,440); transAnimation.setDuration(440); transAnimation.start();

También he intentado con el código de ejemplo a continuación. Pero aún existe el problema.

ObjectAnimator transAnimation = ObjectAnimator.ofFloat(loginLayout, "translationY",0f,0.8f); transAnimation.setDuration(480); transAnimation.start();

Funciona bien en dispositivos de pantalla grande. Pero cuando se trata de dispositivos de pantalla pequeña, se apaga. Quiero mantenerlo en la parte superior de la pantalla, independientemente de los diferentes tamaños de pantalla. Creo que tengo que dar valores en porcentaje (por ejemplo, 0% a 100% o 0 a 100% p). Entonces mi pregunta es cómo dar valores en porcentaje en objectAnimator en Android. También noté una cosa que este objectAnimator se introdujo solo en HoneyComb. Entonces, ¿hay alguna biblioteca de compatibilidad con versiones anteriores para ejecutarlo en versiones bajas? ¿Podría alguien guiarme para encontrar una solución para esto?

También intenté ampliar la Vista y escribir el getter y el setter para la propiedad en offset() . Todavía no se mueve completamente a la parte superior de la pantalla. Aquí está el código que he usado.

@SuppressLint("NewApi") public float getXFraction() { int width = context.getWindowManager().getDefaultDisplay().getHeight(); return (width == 0) ? 0 : (getY()); } @SuppressLint("NewApi") public void setXFraction(float xFraction) { int width = context.getWindowManager().getDefaultDisplay().getWidth(); setY((width > 0) ? (width) : 0); }

Gracias por adelantado


Intente usar una propiedad personalizada para ObjectAnimator, en lugar de crear una vista personalizada con una propiedad personalizada, puede crear una propiedad personalizada que acepte una ''fracción'':

Property<View, Float> property = new Property<View, Float>(Float.TYPE, "translation_x_fraction") { @Override public Float get(View view) { return view.getWidth() <= 0 ? 0 : view.getTranslationX() / view.getWidth(); } @Override public void set(View view, Float value) { view.setTranslationX(view.getWidth() * value); } } ObjectAnimator.ofFloat(view, property, 0f, 1f);


Para usar ObjectAnimator en dispositivos anteriores a Honeycomb, agregue la biblioteca NineOldAndroids a su proyecto y cambie sus importaciones para usar com.nineoldandroids.animation.ObjectAnimator .

Para usar los valores porcentuales en ObjectAnimator en lugar de getXFraction y setXFraction , debe agregar los métodos getYFraction y setYFraction como este

public float getYFraction() { final WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); int height = wm.getDefaultDisplay().getHeight(); return (height == 0) ? 0 : getY() / (float) height; } public void setYFraction(float yFraction) { final WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); int height = wm.getDefaultDisplay().getHeight(); setY((height > 0) ? (yFraction * height) : 0); }

Y luego puede crear el archivo xml project-folder/res/animator/move_bottom.xml como este

<?xml version="1.0" encoding="utf-8"?> <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android" android:duration="500" android:propertyName="yFraction" android:valueFrom="0" android:valueTo="0.8" android:valueType="floatType" />

O crea animaciones en codigo

final LoginLayout loginLayout = (LoginLayout) findViewById(R.id.login_layout); final ObjectAnimator oa = ObjectAnimator.ofFloat(loginLayout, "yFraction", 0f, 0.8f); oa.start();


Si desea crear una animación desde fuera de la pantalla con ObjectAnimator. Puedes hacer esto con el tamaño de pantalla de Android.

@Override public void onCreate(Bundle savedInstanceState) { ... sampleImage = BitmapFactory.decodeResource(getResources(), R.drawable.sample); myImage = (ImageView) findViewById(R.id.image_view); myImage.setImageBitmap(sampleImage); //In case API Level is 14 above. Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); float displayWidth = size.x; //In case API Level is 13 below. //WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE); //Display display = wm.getDefaultDisplay(); //displayWidth = display.getWidth(); animator = ObjectAnimator.ofFloat(myImage, "translationX", displayWidth, 0); animator.setDuration(500); }

Lo siento, si mi sugerencia no entendió el punto.