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 onOpt
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:
public class MainActivity extends Activity {
private Handler handler;
private TextView textView;
private TextUpdateRunnable textUpdateRunnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
textView = (TextView)findViewById(R.id.textView);
Button startButton = (Button)findViewById(R.id.button);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(textUpdateRunnable != null) {
handler.removeCallbacks(textUpdateRunnable);
}
TextUpdateRunnable newTextUpdateRunnable = new TextUpdateRunnable(handler, textView);
textUpdateRunnable = newTextUpdateRunnable;
handler.post(textUpdateRunnable);
}
});
}
private static class TextUpdateRunnable implements Runnable {
private static final int LIMIT = 5;
private int count = 0;
private Handler handler;
private TextView textView;
public TextUpdateRunnable(Handler handler, TextView textView) {
this.handler = handler;
this.textView = textView;
}
public void run() {
if(textView != null) {
textView.setText("here" + count);
count++;
if(handler != null && count < LIMIT) {
handler.postDelayed(this, 3000);
}
}
}
};
}
activity_main.xml: