How can I make an object to move horizontally or vertically in Android?
I am trying to implement a String or TextView开发者_JAVA技巧 that moves from right to left. Thanks for your answers in advance.
I do things like this by handling my owning painting (onDraw()) and by using transfors to handle the shifting locations quickly.
This animates a TextView from right to left. I mostly copied this code from the Android API Demos app. Note that animations should often be described in XML, and not in code, as this example does.
public class Main extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Animation animation = new TranslateAnimation(100, 0, 0, 0);
animation.setDuration(2000);
animation.setRepeatCount(-1);
TextView myTextView = (TextView)findViewById(R.id.my_text_view);
myTextView.setAnimation(animation);
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<TextView
android:id="@+id/my_text_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
I recommend reviewing the following documents on Android animations.
- http://developer.android.com/reference/android/view/animation/package-summary.html
- http://developer.android.com/guide/topics/graphics/view-animation.html
精彩评论