我有3个 Activity :主要->饮料-> DrinkAlcohol
我按顺序浏览它们,但是我想从DrinkAlcohol中获取结果并将其发送给Main。
在DrinkAlcohol中,我使用SetResult;在Main中,我使用onActivityResult。但是我被困在DrinkAlcohol页面上,我做错了什么?
DrinkAlcohol XML按钮
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:layout_marginEnd="24dp"
android:clickable="true"
android:onClick="gotoMain"
app:srcCompat="@drawable/ic_home_black_24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
DrinkAlcohol goto主要功能:
fun gotoMain(view: View){
val radioButtonID = mRg?.checkedRadioButtonId
val rb = findViewById<RadioButton>(radioButtonID!!)
val checkedValue = rb.text.toString().replace("%","").toDouble()
val asu = mSize*checkedValue/60
logDrink(asu)
val intent = Intent(this, MainActivity::class.java)
val returnIntent = this.intent
returnIntent.putExtra("asu", asu)
setResult(Activity.RESULT_OK, returnIntent)
}
MainActivity接收代码:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RETURN_DRINK_ACTIVITY) {
if (resultCode == Activity.RESULT_OK) {
val asu:Double = data!!.extras.get("asu").toString().toDouble()
updateDailyDrinks(asu)
updateDailyBudget(asu)
updateWeeklyBudget(asu)
updateBAC(asu)
}
}
}
我希望获得MainActivity页面,该页面将触发一组Toasts,但实际上我什么也没得到,我只留在DrinkAlcohol Page(Activity)上。
我想念什么?
调用DrinkAlcohol的代码:
fun getDrinkSize(view: View){
val size: Double = view.getTag().toString().toDouble()
Toast.makeText(this, "The Drink is $size", Toast.LENGTH_LONG).show()
var intent = Intent(this,DrinkAlcoholActivity::class.java )
intent.putExtra("size", size)
startActivity(intent)
}
最佳答案
setResult()
不会将您带到任何其他 Activity 。
而不是setResult(Activity.RESULT_OK, returnIntent)
,您应该这样做
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);// If an instance of this Activity already exists, then it will be moved to the front. If an instance does NOT exist, a new instance will be created.
startActivity(intent);
而在您的MainActivity
onCreate()
中,Bundle bundle= getIntent().getExtras();
if(bundle !=null){
// get your data here
}
您不需要
onActivityResult()
。代码在Java中,因为我不知道Kotlin,对不起:)