今天將針對activity的跳轉來複習複習
這次採用bundle來傳值,並區分startActivity()和startActivityForResult()
從Activity1跳轉到Activity2
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
temp = editText.getText().toString();
bundle.putString("input",temp);
intent.putExtras(bundle);
startActivity(intent);
}
});
textView=findViewById(R.id.Text);
button=findViewById(R.id.b2);
Bundle bundle=this.getIntent().getExtras();
String msg=bundle.getString("input");
textView.setText(""+msg);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
從Activity1跳轉到Activity2並等待Activity2結果
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
temp = editText.getText().toString();
bundle.putString("input",temp);
intent.putExtras(bundle);
//更改
startActivityForResult(intent,0);
}
});
用來接收Activity2回傳回來的值,顯示在textView上
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//333是自訂義,要跟Activity2一樣就行
if(resultCode==333){
Bundle bundle=data.getExtras();
String msg=bundle.getString("input");
textView.setText(""+msg);
}
}
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity2.this.setResult(333,intent);
finish();
}
});
intent是要出國的你,bundle是行李箱。