Android:将数据发送回MainActivity

时间:2017-12-02 13:34:50

标签: android kotlin

我有3个活动:主要 - >喝 - >喝含酒精饮料 我按顺序浏览它们,但我想从DrinkAlcohol获取结果并将它们发送到Main。

在DrinkAlcohol中我使用的是 SetResult ,在Main中我正在使用 onActivityResult 。但我被困在DrinkAlcohol页面上,我做错了什么?

DrinkAlcohol XML Button

<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 gotoMain功能:

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)

        }
    }
}

我希望得到一个可以触发一组Toast的MainActivity页面,但实际上我什么都没有留在DrinkAlcohol页面(活动)。

我错过了什么?

调用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)
}

2 个答案:

答案 0 :(得分:2)

setResult()不会将您带到任何其他活动。

而不是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,抱歉:)

答案 1 :(得分:1)

我看到了您的错误,您需要拨打startActivityForResult(intent, request_code)而不是startActivity(intent)才能以onActivityResult方式接收回复:

试试这个:

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)
    startActivityForResult(intent,RETURN_DRINK_ACTIVITY)
}