【问题标题】:How can I call a package-private method in Activity from SurfaceView?如何从 SurfaceView 调用 Activity 中的包私有方法?
【发布时间】:2013-02-15 08:07:38
【问题描述】:

我的 Activity 类中有一个非静态的包私有方法,我想在 SurfaceView 中调用它,例如:surfaceChanged() 或 surfaceDestroyed()。

    public class MyActivity extends Activity {

Camera mCamera = Camera.open();
Camera.Parameters parameters = mCamera.getParameters();
boolean hasFlash = false;
...
    void destroyCamera() {
    flashOff();
    mCamera.stopPreview();
    mCamera.release();
    mCamera = null;
}

void updateCamera() {
    mCamera.setParameters(parameters);
    mCamera.startPreview();
}
...
class CameraView extends SurfaceView implements SurfaceHolder.Callback {
...
    public void surfaceDestroyed(SurfaceHolder holder) {
    destroyCamera();
}
...

有没有更好的方法来做到这一点?我在同一个活动中也有一个 toggleFlash() 方法,因此我可以通过关键监听器在活动中切换闪光灯。

【问题讨论】:

  • 您在问什么非常不清楚。你说SurfaceView,但你的代码中没有提到一个。请更具体。
  • 添加了我试图在活动中调用方法的 SurfaceView 类。可以将活动作为参数传递给重载的构造函数吗?我要问的是从 SurfaceView 类调用 Activity 类中的方法的最佳方法是什么。很抱歉造成混乱:)

标签: android methods android-activity surfaceview package-private


【解决方案1】:

要回答您的评论 - 是的,您可以将 Activity 传递给构造函数来代替 context

SurfaceView view = new SurfaceView(this);

那么,只要你确定context 就是Activity,你就可以将它转换成Activity 来调用方法:

//call inside the view
((MyActivity) getContext()).methodToCall(); 

其他选项包括提供对您的Activity 的静态引用,或通过弱引用静态访问您的活动,例如:

public static WeakReference<MyActitivity> getActivity(){
    return new WeakReference<MyActivity>(self);// self is a static instance of MyActivity
}

您可以通过在onCreate 或默认构造函数中分配Activity 来获得对Activity 的静态引用:

private static MyActivity self;

public MyActivity()
{
    super();
    self = this;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 2015-07-06
    • 2011-05-01
    • 2017-07-20
    • 2019-03-24
    • 1970-01-01
    相关资源
    最近更新 更多