将数据从surfaceView传递到另一个活动

时间:2013-07-12 22:48:16

标签: java android android-activity bundle surfaceview

以下代码的解释:我正在尝试完成的任务是从我的surfaceview活动(surfaceActivity)向我的主要活动(mainActivity)发送一个布尔值。下面是我的代码的4个部分,mainActivity的初始化,surfaceActivity的初始化,我如何发送布尔值,以及我如何接收布尔值。显然我用来发送/接收信息的代码是大多数人在互联网上取得成功的原因,只是我的情况有点不同,因为我有两个活动,但是surfaceActivity是通过mainActivity设置的,因此不是真的独立。

我的主要活动:

public class MainActivity extends Activity {

      public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(new surfaceActivity(this));

           private Bundle bundle;
      }
 }

然后导致我的surfaceView

public class surfaceActivity extends SurfaceView  implements SurfaceHolder.Callback {
     private MainThread thread;
     private Context context;

     public surfaceActivity(Context context) {
     super(context);
     getHolder().addCallback(this);
     thread = new MainThread(getHolder(), this);

     this.context = context;

     setFocusable(true);
     }

然后当注册屏幕上的触摸时:

Intent i = new Intent(context, MainActivity.class);             
Bundle bundle = new Bundle();
bundle.putBoolean("boo",true);
i.putExtras(bundle);
startActionMode((Callback) i);

然后在MainActivity类中不断重复循环:

if (bundle != null)
{
    bundle = getIntent().getExtras();
    Boolean stuff = bundle.getBoolean("boo"); 
}

此外,大多数人一直在使用startActivity(i);但eclipse将其更正为startActionMode((Callback)i);

提前非常感谢!

2 个答案:

答案 0 :(得分:1)

MainActivity是一个Activity,SurfaceActivity(即使名称为Activity)只是一个已添加为MainActivity的内容视图的View。 MainActivity可以将SurfaceActivity的引用声明为Instance变量,然后它可以从SurfaceActivity读取值。

基于Intent的机制通常用于在Activities之间传递值,在您的情况下,您没有2个Activity。您有一个活动和一个视图。

答案 1 :(得分:0)

要从MainActivity(在OP示例SurfaceView中)调用SurfaceActivity中的方法,您可以这样做:

MainActivity设置:

public class MainActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new surfaceActivity(this));
        private Bundle bundle;
    }

    // Method to be called from the SurfaceView
    public void callMe(String valuePassed) {
        Log.d("DEBUG","MainActivity was passed ["+ valuePassed +"]");
    }
}

SurfaceView设置:

public class SurfaceActivity extends SurfaceView 
                             implements SurfaceHolder.Callback {

    private MainThread thread;
    private Context context;

    public SurfaceActivity(Context context) {
        super(context);
        getHolder().addCallback(this);
        thread = new MainThread(getHolder(), this);

        this.context = context;

        setFocusable(true);
    }

    // This is where and how you make the call to MainActivity.
    // You cast the context as the MainActivity and call the method.
    private void passToMainActivity(String valToPass) {
        ((MainActivity) context).callMe(valToPass);
    }
}