// 目錄結構
//運行結果
//SimpleDemo01Activity.java
- package sn.len.simple;
-
- import Android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
-
- public class SimpleDemo01Activity extends Activity implements OnClickListener
- {
-
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- View openOtherAct=findViewById(R.id.openotheractivity);
- openOtherAct.setOnClickListener(this);
-
- }
-
- @Override
- public void onClick(View v)
- {
- switch (v.getId())
- {
- case R.id.openotheractivity:
-
- Intent intent=new Intent(this,OtherActivity.class);
- //傳參寫法1
- intent.putExtra("name", "楊煉");
- intent.putExtra("age", 18);
- //傳參寫法2
- Bundle bundle=new Bundle();
- bundle.putString("name", "xiaoyang");
- bundle.putInt("age", 18);
- intent.putExtras(bundle);
- //激活另一個Activity
- //startActivity(intent);
- startActivityForResult(intent, 100);
- break;
- default:
- break;
- }
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data)
- {
- if(resultCode==20) //判斷其它關閉
- {
- String str=data.getExtras().getString("close");
- Log.i("CLOSE", str);
- }
- else
- {
- Log.i("CLOSE", "叫你不按按鈕關閉,如果不判斷響應代碼就出異常了吧。");
- }
-
- }
-
- }
//OtherActivity.java
- package sn.len.simple;
-
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.TextView;
-
- public class OtherActivity extends Activity implements OnClickListener
- {
-
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.other);
- Intent intent=this.getIntent();
- //取得方法1
- String name1=intent.getStringExtra("name");
- int age1=intent.getIntExtra("age",0);
- //取得方法2
- String name2=intent.getExtras().getString("name");
- int age2=intent.getExtras().getInt("age");
- TextView textView1=(TextView)findViewById(R.id.simplepro1);
- TextView textView2=(TextView)findViewById(R.id.simplepro2);
- textView1.setText("第一種:name"+name1+" age"+age1);
- textView2.setText("第二種:name"+name2+" age"+age2);
-
-
-
- Button close=(Button)findViewById(R.id.close);
- close.setOnClickListener(this);
-
- }
-
- @Override
- public void onClick(View v)
- {
- switch(v.getId())
- {
- case R.id.close:
- Intent intent2=new Intent();
- intent2.putExtra("close", "已經關掉了");
- setResult(20, intent2);
- finish();
- break;
- }
-
- }
-
-
- }