不像上一篇講到的AB互傳溝通
因此Bundle傳值時,給出的畫面是一個新的、乾淨的初始畫面
範例:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainActivity extends AppCompatActivity { | |
private Button widget2; | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
widget2 =(Button)findViewById(R.id.btnNext2); | |
//接收SecondActivity bundle傳來的參數 | |
Bundle param = getIntent().getExtras(); | |
if(param !=null) | |
{ | |
setTitle(param.getString("bparam")); | |
} | |
//利用bundle傳參數到ScondActivity | |
widget2.setOnClickListener(new Button.OnClickListener() { | |
public void onClick(View v) { | |
Intent intent2 = new Intent(); | |
Bundle bundle= new Bundle(); | |
bundle.putString("sourse","bundle from Main"); | |
intent2.setClass(MainActivity.this, widgetActivity2.class); | |
intent2.putExtras(bundle); | |
startActivity(intent2); | |
} | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SecondActivity extends AppCompatActivity { | |
private Button prev; | |
@Override | |
public void onCreate(Bundle savedInstanceState){ | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.widget2); | |
//接收Main 傳來的參數 | |
Bundle bundle = getIntent().getExtras(); | |
if(bundle !=null) | |
{ | |
setTitle(bundle.getString("sourse")); | |
} | |
prev =(Button)findViewById(R.id.button1); | |
//Bundle傳送參數到Main | |
prev.setOnClickListener(new Button.OnClickListener() { | |
public void onClick(View v) { | |
Intent intent = new Intent(); | |
intent.setClass(widgetActivity2.this, MainActivity.class); | |
// Bundle 傳送參數 | |
Bundle param = new Bundle(); | |
param.putString("bparam", "from widget2"); | |
intent.putExtras(param); | |
startActivity(intent); | |
} | |
}); | |