将值从视图类传递到活动类?

问题描述 投票:-2回答:1

我有这个迷你游戏和两个活动。我使用了一个意图来命令我的应用程序从活动1(只是一个菜单屏幕)转到活动2.但是,我希望将游戏得分从活动2返回到活动1,当gameIsOver,但我的第二个活动读取:

公共类MainActivity扩展AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(new DrawView (this));

}

}

所以我的活动实际上是在DrawView类中运行,它扩展了View类。我如何从View Class返回活动1?

android
1个回答
0
投票

这里需要两件事:

首先 - 您的自定义视图需要将其分数报告给托管Activity2

为了实现这个目的,

public interface OnResult {
    void onResult(int result);
}

让你的Activity2实现OnResult,让你的自定义DrawView类有一个字段OnResult resultCallback;,让活动把它自己作为这个字段。例如

@覆盖

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    DrawView view = new DrawView (this); // "this" here as a Context object
    view.setResultCallback(this); // "this" here as the OnResult listener object
    setContentView(view);
}

而且,从你的自定义视图中有结果调用resultCallback.onResult()(即调用活动)

通过接口here阅读有关回调机制的更多信息

第二 - 在你的activity2中将答案传递回活动1

首先,从activity1启动activity2时,不要只使用startActivity()启动它,而是使用startActivityForResult()启动它以获得结果

并在第一步的onResult()的activity2实现中,通过意图返回结果并完成活动 -

Intent intent = new Intent();
intent.putExtra("editTextValue", "value_here")
setResult(RESULT_OK, intent);        
finish(); 

阅读更多关于将返回值从一个活动传递到另一个活动的信息here(来自@Uma Sankar)

© www.soinside.com 2019 - 2024. All rights reserved.