在一個Activity中可使用系統提供的startActivity(Intent intent)方法打開新的Activity,在打開新的Activity前,你能夠決定是否爲新的Activity傳遞參數。java
第一種:打開新的Activity,不傳遞參數android
public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btnOpen=(Button)this.findViewById(R.id.btnOpen); btnOpen.setOnClickListener(new View.OnClickListener(){ public void onClick(View v) { //新建一個顯式意圖,第一個參數爲當前Activity類對象,第二個參數爲你要打開的Activity類 startActivity(new Intent(MainActivity.this, OtherActivity.class)); } }); } }
第二種:打開新的Activity,並傳遞若干個參數給它app
package com.ljq.activitys; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btnOpen=(Button)this.findViewById(R.id.btnOpen); btnOpen.setOnClickListener(new View.OnClickListener(){ public void onClick(View v) { //第一種:打開新的Activity,不傳遞參數 //新建一個顯式意圖,第一個參數爲當前Activity類對象,第二個參數爲你要打開的Activity類 //startActivity(new Intent(MainActivity.this, OtherActivity.class)); //第二種:打開新的Activity,並傳遞若干個參數給它 Intent intent=new Intent(MainActivity.this, OtherActivity.class); //Bundle類用做攜帶數據 Bundle bundle=new Bundle(); bundle.putString("name", "linjiqin"); bundle.putInt("age", 24); //附帶上額外的數據 intent.putExtras(bundle); startActivity(intent); } }); } }
在新的Activity中接收前面Activity傳遞過來的參數ide
package com.ljq.activitys; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class OtherActivity extends Activity { private final static String TAG="OtherActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.other); //在新的Activity中接收前面Activity傳遞過來的參數 Bundle bundle=this.getIntent().getExtras(); String name=bundle.getString("name"); Integer age=bundle.getInt("age"); Log.i(TAG, name+" : "+age); } }