Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you do not want to have lots of threads running at once with staggered delays you can do something like the following:</p> <pre><code>public class MainActivity extends Activity { private int viewsAddedCount = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button b = (Button)findViewById(R.id.button1); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setEnabled(false); Thread thread = new delayedViewAdditionThread(); thread.start(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } public class delayedViewAdditionThread extends Thread { private android.os.Handler handler = new android.os.Handler() { @Override public void handleMessage(android.os.Message msg) { switch(msg.what) { case 0 : addTextView(); break; case 1 : Button b = (Button)findViewById(R.id.button1); b.setEnabled(true); break; default : break; } } }; @Override public void run() { for(int i = 0; i &lt; 4; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } handler.sendEmptyMessage(0); } handler.sendEmptyMessage(1); } private void addTextView() { TextView tv = new TextView(MainActivity.this); tv.setText("TextView No. " + String.valueOf(viewsAddedCount + 1)); tv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); LinearLayout ll = (LinearLayout)findViewById(R.id.expandingLayout); ll.addView(tv); viewsAddedCount++; } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload