由于老师出了这么一道作业题: 上课在睡觉的我一脸懵逼,然后查了下老师说的 startActivityForResult发现此方法已经过时,将要或已经被Activity Result Api取代 然后就看了下这个东西的用法,网上多数为kt的文章,java较少
这里推荐两篇比较好的文章 搞懂 Activity Result API (一) Android Activity之间的数据返回
下面贴出我的代码 MainActivity :
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
Button bt;
EditText in,out;
ActivityResultContracts.StartActivityForResult contract = new ActivityResultContracts.StartActivityForResult();
ActivityResultCallback<ActivityResult> callBack= new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
Intent data = result.getData();
out.setText(data.getStringExtra("callBackText"));
}
};
private ActivityResultLauncher<Intent> mActivityBLauncher = registerForActivityResult(contract, callBack);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt=findViewById(R.id.ac1bt);
in=findViewById(R.id.ac1in);
out=findViewById(R.id.ac1out);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("in",in.getText().toString());
mActivityBLauncher.launch(intent);
}
});
}
}
MainActivity 2:
package com.example.myapplication;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.LinearLayout;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity2 extends AppCompatActivity {
EditText in;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent= getIntent();
String intxt=intent.getStringExtra("in");
in=findViewById(R.id.ac2in);
in.setText(intxt);
}
@Override
public void onBackPressed() {
Intent intent = new Intent();
String data = in.getText().toString();
intent.putExtra("callBackText",data);
setResult(2,intent);
finish();
}
}
|