安卓在不同的activity之间传递返回数据
2017-03-08 本文已影响30人
东京的雨不会淋湿首尔
新建一个FirstActivity :
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
Button but1 = (Button) findViewById(R.id.but1);
but1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
#显示intent,向SecondActivity传递数据
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
String data = "testtest";#比如传递string类数据
intent.putExtra("first_input",data);#相当于key为first_input,value为data
startActivityForResult(intent,1);#1表示request_code可以为任意的确定值
}
});
}
#返回值处理函数,可以先看下面的SecondActivity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{#第一个参数为上面startActivityForResult中所填的request_code,第二个参数resultCode为后面另一个activity(SecondActivity)的函数中设置的返回code,data为SecondActivity中返回的数据
switch (requestCode){
case 1:
if(resultCode == RESULT_OK){
String da = data.getStringExtra("feedback");
Log.d("FirstActivity",da);
}
}
}
第一个activity对应xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button android:id="@+id/but1"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="click"
/>
</LinearLayout>
现在另建一个SecondActivity:
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Button button = (Button) findViewById(R.id.but_2);
Intent intent = getIntent(); #获取FirstActivity 传递的intent
String a = intent.getStringExtra("first_input"); #取得key为first_input的值value
Log.d("SecondActivity",a);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(); #新建显式的intent
intent.putExtra("feedback","feedback info"); #把返回值对应key,value存入intent
setResult(RESULT_OK,intent); #通过setResult函数把intent返回给firstactivity,参数1一般有默认值RESULT_OK,RESULT_CANCELLED等
finish(); #完成后销毁activity2
}
});
}
}
对应xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.javascript.activitytest.SecondActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="but2"
android:id="@+id/but_2"/>
</android.support.constraint.ConstraintLayout>