Info:startActivty 与 startActivityForResult区别
(1):startActivity 启动了其他Activity之后不会再回调过来,此时启动者与被启动者在启动后没有联系了。
(2):startActivityForResult 可以进行回调,之后有联系。
1:activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/tv_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btn_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="button1"
android:layout_below="@id/tv_show"/>
</RelativeLayout>
2:MainActivity.java
public class MainActivity extends Activity {
private Button btn1=null;
private TextView tvShow=null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1=(Button)findViewById(R.id.btn_1); btn1.setOnClickListener(new OnClickListener(){
public void onClick(View view){
Intent intent=new Intent(MainActivity.this,OtherActivity.class);
startActivityForResult(intent,100);
}
});
} @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data); if(requestCode==100 && resultCode==Activity.RESULT_OK){
String info=data.getExtras().getString("info");
tvShow=(TextView)findViewById(R.id.tv_show);
tvShow.setText(info);
}
}
}
3:activity_other.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/et_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="input info"/>
<Button
android:id="@+id/btn_back"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button Back"
android:layout_below="@id/et_input"/>
</RelativeLayout>
4:OtherActivity.java
public class OtherActivity extends Activity {
private EditText etInfo=null;
private Button btnBack=null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other); etInfo=(EditText)findViewById(R.id.et_input);
btnBack=(Button)findViewById(R.id.btn_back); btnBack.setOnClickListener(new OnClickListener(){
public void onClick(View view){
Intent intent=new Intent();
String info=etInfo.getText().toString();
intent.putExtra("info", info); setResult(Activity.RESULT_OK,intent);
finish(); //关闭当前的Activity
}
});
}
}