Просмотр анимации позади другого макета
Я пытаюсь анимировать представление для другого макета, но у меня проблема, потому что мой взгляд за компоновкой. Я попробовал поставить android:animateLayoutChanges="true"
, но безуспешно.
Мой код:
layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true">
<RadioButton
android:id="@+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New RadioButton" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:animateLayoutChanges="true"
android:background="#ffffff">
</LinearLayout>
</RelativeLayout>
Мой класс активности:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
float x = 300;
float y = 300;
RadioButton button = (RadioButton) findViewById(R.id.radioButton);
button.animate().setDuration(10000).x(x).y(y);
}
}
Ответы
Ответ 1
Элементы будут рисоваться в том же порядке, что и в макете. Для вашего макета RadioButton будет рисовать сначала, а затем LinearLayout. Если они перекрываются, LinearLayout будет нарисован поверх RadioButton.
Решение № 1:
Переверните порядок RadioButton и LinearLayout, чтобы RadioButton всегда рисовался последним.
<RelativeLayout
android:id="@+id/final_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="30dp"
android:background="#ffffff">
</RelativeLayout>
<RadioButton
android:id="@+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New RadioButton" />
Более строгие объяснения на сайте Android Developer.
Решение Part # 2:
Не связанный с тем, что я сделал выше, но, вероятно, не менее важно, вам нужно запустить аниматор. Обновленный источник ниже:
public class MainActivity extends AppCompatActivity {
private RadioButton mRadioButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRadioButton = (RadioButton) findViewById(R.id.radioButton);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
float x = 300;
float y = 300;
ViewPropertyAnimator animator = mRadioButton.animate().setDuration(10000).x(x).y(y);
animator.setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {}
@Override
public void onAnimationEnd(Animator animation) {
Log.d(TAG, "onAnimationEnd");
}
@Override
public void onAnimationCancel(Animator animation) {}
@Override
public void onAnimationRepeat(Animator animation) {}
})
animator.start();
}
private static final String TAG = MainActivity.class.getSimpleName();
}
Протестировано, анимируется при запуске приложения в Android 5.1.
Ответ 2
просто укажите все свойства элемента layout xml как android:clipChildren="false"
и android:clipToPadding="false"
. и не забывайте делать animatedView.bringToFront()
имеют такую же проблему до месяца и нашли решение после продолжительной работы через пару дней. Найди мою очередь. здесь
Ответ 3
Позвольте мне предоставить вам решение относительно экрана 480X854 пикселей mdpi
![480X854 pixel screen]()
Сценарий 1: вы хотите, чтобы RadioButton пересекал LinearLayout с RelativeLayout как родительскую ViewGroup, чем , вам нужно исправить ваш z-порядок. Создайте изменения, как показано ниже. Анимация начинается с точки A (0,0) до точки C (300,300) от RelativeLayout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:background="#ffffff">
</LinearLayout>
<RadioButton
android:id="@+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New RadioButton"
/>
</RelativeLayout>
Сценарий 2: вы хотите, чтобы RadioButton анимировался на LinearLayout с LinearLayout в качестве родительской ViewGroup, чем вам нужно установить макет, как показано ниже. Анимация начинается с точки B (20,20) (согласно значению layout_margin
) до точки D (320,320) от RelativeLayout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:background="#ffffff">
<RadioButton
android:id="@+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New RadioButton"
/>
</LinearLayout>
</RelativeLayout>
Сценарий 3. Вы хотите, чтобы RadioButton анимировался в LinearLayout с LinearLayout в качестве родительской ViewGroup, а ваше значение x или y выходит за границы границ LinearLayout в любом направлении, например. x = 800 > 480 пикселей или Y = 1200 > 854 пикселя
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
<!-- Allow all the children to go out of their parent boundaries -->
android:clipChildren="false"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
<!-- Allow all the children to go out of their parent boundaries -->
android:clipChildren="false"
<!-- Do not clip the children at the padding i.e. allow to children go
beyond the padding -->
android:clipToPadding="false"
android:background="#ffffff">
<RadioButton
android:id="@+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New RadioButton"
/>
</LinearLayout>
</RelativeLayout>
Я надеюсь, что это поможет...
Счастливое кодирование...
Ответ 4
Я не уверен, чего вы пытаетесь достичь, но если вы перемещаете дочерний элемент View
вне своего контейнера, вам нужно отключить атрибуты clipToChilder
и clipToPadding
на контейнере, чтобы увидеть дочерний элемент, перемещающийся вне родителя:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false"
android:clipToPadding="false">
...
</RelativeLayout>
В любом случае, если вы сталкиваетесь с проблемой z-order на каком-либо представлении, вы можете использовать метод bringToFront()
; в вашем случае:
final RadioButton button = (RadioButton) findViewById(R.id.radioButton);
button.animate().setDuration(10000).x(x).y(y).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
button.bringToFront();
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
Ответ 5
Основываясь на комментарии sir Karaokyo, на который вы ответили, я предлагаю вам то, что вы хотите
RadioButton r1; // suppose you already referenced it
LinearLayout l1; // //
Animation anim = AnimationUtils.loadAnimation(getBaseContext(), R.anim.abc_slide_in_top);
// the R.anim. blah blah is the preferred animation you want
//when the time comes
if(r1.getParent() != null)
((ViewGroup)r1.getParent()).removeView(r1);
l1.addView(r1);
r1.startAnimation(anim);
// you can create an animation listener and add the view when the animation
//starts
Ловушка здесь, она будет выглядеть так, как вы этого хотели.
Ответ 6
Самое простое решение - попытаться передать в xml так, чтобы RadioButton отображался после LinearLayout.
Вызов showchildTofront (yourradiobutton) перед запуском анимации
или
Если вы хотите больше контролировать порядок рисования, то Extend RelativeLayout и переопределить
protected int getChildDrawingOrder (int childCount, int i)