Activity 利用Intent 转换到另一个Activity

在Android 中,

要从一个Activity 中呼叫另一个Activity,

就必须使用 Intent 物件,

请参考以下范例(这里就不列出Layout XML 档案内容了) :

来源Activity 程式码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class helloWorld extends Activity {
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
 
      // 设定Layout 为main.xml
      setContentView( R.layout.main );
 
      // 按钮物件
      Button b1 = (Button)findViewById( R.id.button1 );
 
      // Button 的OnClick Trigger
      b1.setOnClickListener( new OnClickListener(){
         public void onClick(View v) {
 
            // 指定要呼叫的Activity Class
            Intent newAct = new Intent() ;
            newAct. setClass ( helloWorld .this , helloWorld2 .class );
 
            // 呼叫新的Activity Class
            startActivity ( newAct );
 
            // 结束原先的Activity Class
            helloWorld .this.finish() ;
        }
      });  
   }
}

目的Activity 程式码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
 
      // 设定Layout 为main2.xml
      setContentView( R.layout.main2 );
 
      // 按钮物件
      Button b1 = (Button)findViewById( R.id.button1 );
 
      // Button 的OnClick Trigger
      b1.setOnClickListener( new OnClickListener(){
         public void onClick(View v) {
 
            // 指定要呼叫的Activity Class
            Intent newAct = new Intent() ;
            newAct. setClass ( helloWorld2 .this , helloWorld .class );
 
            // 呼叫新的Activity Class
            startActivity ( newAct );
 
            // 结束原先的Activity Class
            helloWorld2 .this.finish() ;
         }
      });
   }
}

AndroidManifest.xml 要加入第二个Activity,不然呼叫时会有问题:



posted @ 2012-03-07 16:58  ligo  阅读(322)  评论(0编辑  收藏  举报