我需要一个从左到右移动的按钮,每当我点击它时,它都会做一些事情。我开始知道我需要使用Property Animation这样做。但我对它很失落。 这是我的main.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: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=".MainActivity" >
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="39dp"
android:layout_marginTop="106dp"
android:text="Button" />
如何使用属性动画编辑我的.java文件以从左到右为其设置动画?
答案 0 :(得分:3)
查看本教程Android Animations。
为布局设置动画的最简单方法是执行以下操作:
your_layout.animate().translationX(your_layout.getWidth()).setDuration(500).setInterpolator(new AccelerateDecelerateInterpolator());
答案 1 :(得分:1)
我会按以下方式进行:
public class MyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//new GetUrl().execute(20);
// Test XML Files
//testXMLFiles();
final Button speakButton = (Button)findViewById(R.id.play);
speakButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
// TODO: DO something!
}
});
final ObjectAnimator horizontalAnimator = ObjectAnimator.ofInt(new ButtonAnimatorHelper(speakButton), "marginLeft", 0, 600);
horizontalAnimator.setDuration(2000);
horizontalAnimator.setRepeatCount(ValueAnimator.INFINITE);
horizontalAnimator.setRepeatMode(ValueAnimator.REVERSE);
horizontalAnimator.setInterpolator(new LinearInterpolator());
horizontalAnimator.start();
}
/**
* Helper class for button animation
*/
private static class ButtonAnimatorHelper {
final Button mButton;
/**
* Default constructor
* @param speakButton
*/
public ButtonAnimatorHelper(final Button button) {
mButton = button;
}
public void setMarginLeft(final int margin) {
final ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mButton.getLayoutParams();
params.leftMargin = margin;
mButton.setLayoutParams(params);
}
}
}
为了更好地理解属性动画,我建议this session from Google I/O 2013,当然还有the tutorial here。