How To Repeatedly Update Android Textview To Simulate Animation
I would like the text in a TextView to constantly change once a button in the menu is pressed. Here is my menu's onOptionsItemSelected: public boolean onOptionsItemSelected(MenuIte
Solution 1:
You can use a Handler
and a Runnable
for your purpose. I'm sharing an edited code which I currently use just like a purpose of yours.
You can directly copy the class and layout, then try it.
Main idea is using a Handler
with its post
and postDelayed
methods with a Runnable
. When you pust the button, it start to change text on every 3 seconds. If you push the button again it resets itself.
Try this code, try to understand it. Handler
s can be used for many purpose to change UI. Read more about it.
MainActivity.java:
publicclassMainActivityextendsActivity {
private Handler handler;
private TextView textView;
private TextUpdateRunnable textUpdateRunnable;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = newHandler();
textView = (TextView)findViewById(R.id.textView);
ButtonstartButton= (Button)findViewById(R.id.button);
startButton.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View v) {
if(textUpdateRunnable != null) {
handler.removeCallbacks(textUpdateRunnable);
}
TextUpdateRunnablenewTextUpdateRunnable=newTextUpdateRunnable(handler, textView);
textUpdateRunnable = newTextUpdateRunnable;
handler.post(textUpdateRunnable);
}
});
}
privatestaticclassTextUpdateRunnableimplementsRunnable {
privatestaticfinalintLIMIT=5;
privateintcount=0;
private Handler handler;
private TextView textView;
publicTextUpdateRunnable(Handler handler, TextView textView) {
this.handler = handler;
this.textView = textView;
}
publicvoidrun() {
if(textView != null) {
textView.setText("here" + count);
count++;
if(handler != null && count < LIMIT) {
handler.postDelayed(this, 3000);
}
}
}
};
}
activity_main.xml:
<LinearLayoutxmlns: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:orientation="vertical" ><Buttonandroid:id="@+id/button"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="BUTTON" /><TextViewandroid:id="@+id/textView"android:layout_width="match_parent"android:layout_height="wrap_content" /></LinearLayout>
Solution 2:
See on this answer https://stackoverflow.com/a/3039718/2319589 how to use the Sleep
with the Runnable()
and implement your code this way.
Should work.
Good luck :)
Post a Comment for "How To Repeatedly Update Android Textview To Simulate Animation"