24 得到Activity返回的数据
得到Activity返回的数据
相关代码及截图:
MainActivity.java
package com.example.getbackdata; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { public final static int REUEST_CODE=1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void btn_start_otherActivity(View view) { //步骤一 Intent intent=new Intent(this,OtherActivity.class); startActivityForResult(intent,REUEST_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode){ case REUEST_CODE: TextView textView = findViewById(R.id.textView); textView.setText(data.getStringExtra("result")); default: break; } } }
OtherActivity.java
package com.example.getbackdata; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class OtherActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_other); } public void btn_back(View view) { //步骤二 EditText editText=findViewById(R.id.editText); Intent intent=new Intent(); intent.putExtra("result",editText.getText().toString()); this.setResult(0,intent); finish(); } }
运行截图:
1.初识界面
2.启动OtherActivity
3.返回界面