我是Android的新手,我正在关注thenewboston的教程系列。
目前正在观看视频34:动画和过渡。
此视频的目标是动画从左上方到右下角的按钮。
以下是 MainActivity 类的代码:
package com.example.jarno.a34_animations;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.transition.TransitionManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "debugMessage";
ViewGroup mainLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "set activity_main");
mainLayout = (ViewGroup) findViewById(R.id.mainLayout);
// Click screen
mainLayout.setOnTouchListener(
new RelativeLayout.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
moveButton();
Log.i(TAG, "button click");
return true;
}
}
);
}
public void moveButton() {
View animationButton = findViewById(R.id.animationButton);
// Smooth transition
TransitionManager.beginDelayedTransition(mainLayout);
// Change position
RelativeLayout.LayoutParams positionRules = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
positionRules.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
positionRules.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
mainLayout.setLayoutParams(positionRules);
// Change size
ViewGroup.LayoutParams sizeRules = animationButton.getLayoutParams();
sizeRules.width = 450;
sizeRules.height = 300;
animationButton.setLayoutParams(sizeRules);
}
}
activity_main.xml中
<?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:id="@+id/mainLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.jarno.a34_animations.MainActivity">
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="@+id/animationButton" />
</RelativeLayout>
通过评论此部分,应用程序不会崩溃。
// Change position
RelativeLayout.LayoutParams positionRules = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
positionRules.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
positionRules.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
mainLayout.setLayoutParams(positionRules);