Activity之間的跳轉和數據傳輸
阿新 • • 發佈:2018-11-11
code 之間 接收 listener protect con click ner class
1.顯式跳轉
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
bt1= (Button) findViewById(R.id.btn_jumptoB);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 顯式
Intent intent=new Intent(AActivity.this,BActivity.class);
// Intent intent=new Intent();
intent.setAction("sankuai.com");
Bundle bundle=new Bundle();
bundle.putString("name","lijing");
intent.putExtras(bundle);
startActivityForResult(intent,10086);
}
});
}
2.隱式跳轉
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
bt1= (Button) findViewById(R.id.btn_jumptoB);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 顯式
// Intent intent=new Intent(AActivity.this,BActivity.class);
// 隱式
Intent intent=new Intent();
intent.setAction("sankuai.com");
Bundle bundle=new Bundle();
bundle.putString("name","lijing");
intent.putExtras(bundle);
startActivityForResult(intent,10086);
}
});
}
Manifest文件中針對目標activity
<activity android:name=".jump.BActivity"
android:label="B">
<intent-filter>
<action android:name="sankuai.com" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
3.把數據傳遞到目標activity
發:
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
bt1= (Button) findViewById(R.id.btn_jumptoB);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(AActivity.this,BActivity.class);
Bundle bundle=new Bundle();
bundle.putString("name","lijing");
intent.putExtras(bundle);
startActivityForResult(intent,10086);
}
});
}
收:
在目標activityz中
String name=getIntent().getStringExtra("name");
4.返回數據給上一個活動
public void onClick(View view) {
Intent intent=new Intent(AActivity.this,BActivity.class);
Bundle bundle=new Bundle();
bundle.putString("name","lijing");
intent.putExtras(bundle);
startActivityForResult(intent,10086);--10086是requestcode
}
在目標activity中
buttonxx.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent();
intent.putExtra("visitor","999999");
setResult(RESULT_OK,intent);--RESULT_OK是resultcode
finish();
}
});
在BActivity被finish()銷毀以後,AActivity會調用
onActivityResult方法,所以需要重寫這個方法來接收來自B的傳遞數據
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case 10086:
if (resultCode==RESULT_OK){
String result=data.getStringExtra("visitor");
Log.d("visitor",result);
}
break;
}
總結:
startActivity只能傳遞給目標activity數據
startActivityForResult:既能傳遞數據,也能從另一個activity中回調數據給自己,如果兩種都需要,可以直接使用
startActivityForResult。
Activity之間的跳轉和數據傳輸