public class MainActivity extends Activity { |
02 | |
03 | private final static int CHANGE = 1 ; |
04 |
05 | private static TextView textView; |
06 | |
07 | private static Handler handler = new Handler(){ |
08 |
09 | @Override |
10 | public void handleMessage(Message msg) { |
11 | switch (msg.what) { |
12 | case CHANGE : |
13 | textView.setText(msg.obj + "" ); |
14 | } |
15 | } |
16 | |
17 | }; |
18 | |
19 | @Override |
20 | public void onCreate(Bundle savedInstanceState) { |
21 | super .onCreate(savedInstanceState); |
22 | setContentView(R.layout.activity_main); |
23 | textView = (TextView) findViewById(R.id.hello); |
24 | |
25 | |
26 | new Thread() { |
27 | |
28 | public void run() { |
29 | for ( int i= 0 ;i< 100 ;i++) { |
30 | try { |
31 | Thread.sleep( 1000 ); |
32 | } catch (InterruptedException e) { |
33 | e.printStackTrace(); |
34 | } |
35 | Message msg = new Message(); |
36 | msg.what = MainActivity.CHANGE; |
37 | msg.obj = i; |
38 | MainActivity.handler.sendMessage(msg); |
39 | } |
40 | } |
41 | }.start(); |
42 | } |
43 | } |
2. [代码]用activity控制dialog显示值的变化
01 | public class MainActivity extends Activity { |
02 | |
03 | private final static int CHANGE = 1 ; |
04 |
05 | private static TextView text2; |
06 |
07 | private static TextView text5; |
08 | |
09 | private static Handler handler = new Handler(){ |
10 |
11 | @Override |
12 | public void handleMessage(Message msg) { |
13 | switch (msg.what) { |
14 | case CHANGE : |
15 | text2.setText(msg.obj + "" ); |
16 | text5.setText(msg.obj + "" ); |
17 | } |
18 | } |
19 | |
20 | }; |
21 | |
22 | @Override |
23 | public void onCreate(Bundle savedInstanceState) { |
24 | super .onCreate(savedInstanceState); |
25 | setContentView(R.layout.activity_main); |
26 |
27 | Dialog dialog = new Dialog( this ); |
28 | dialog.setContentView(R.layout.custom_dialog); |
29 | dialog.setTitle( "test" ); |
30 | text2 = (TextView) dialog.findViewById(R.id.text2); |
31 | text5 = (TextView) dialog.findViewById(R.id.text5); |
32 | dialog.show(); |
33 | |
34 | new Thread() { |
35 | |
36 | public void run() { |
37 | for ( int i= 0 ;i< 100 ;i++) { |
38 | try { |
39 | Thread.sleep( 1000 ); |
40 | } catch (InterruptedException e) { |
41 | e.printStackTrace(); |
42 | } |
43 | Message msg = new Message(); |
44 | msg.what = MainActivity.CHANGE; |
45 | msg.obj = i; |
46 | MainActivity.handler.sendMessage(msg); |
47 | } |
48 | } |
49 | }.start(); |
50 | } |
51 | } |