首页 > 解决方案 > 无法从扩展 Runnable 并嵌套在布局中的自定义 SurfaceView 中找到公共方法

问题描述

所以这个应用程序有一个自定义的 SurfaceView,它扩展了 Runnable。

起初 myView 直接在 MainActivity 中使用,而不是通过任何布局,它的工作方式应该如此。通过 run() 显示的内容取决于我从 MainActivity 传递的屏幕高度。然后我决定嵌套视图并使其内容依赖于布局的高度。

在将它嵌套在 LinearLayout 下后,我在 init() 的代码中使用了 getLayoutParams(),然后 MainActivity 停止识别 pause() 和 resume() 函数。我想我可能以错误的方式在 MainActivity 中声明自定义视图,但我找不到任何相关来源

主要活动

    public class MainActivity extends Activity {

    private SurfaceView myView1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myView1 = findViewById(R.id.myView);
        setContentView(R.layout.myParentLayout);
    }
    @Override
    protected void onPause(){
        super.onPause();
        myView1.pause();    //cannot recognise this function
    }
    @Override
    protected void onResume(){
        super.onResume();
        myView1.resume();   //and this function
    }
}

我的观点

class myView extends SurfaceView implements Runnable {
    public Context context;
    private SurfaceHolder surfaceHolder;
    private boolean running;
    private Thread thread;
    private myClass l;   //imported classes
    public myView(Context context) {
        super(context);
        init();
    }
    public myView(Context context, AttributeSet attrs){
        super(context,attrs);
        init();
    }
    public myView(Context context, AttributeSet attrs, int defStyleAttr){
        super(context,attrs, defStyleAttr);
        init();
    }
    private void init(){
        surfaceHolder = getHolder();
        int x = getLayoutParams().width;  //happened after i added this
        l = new myClass(x);
    }
    @Override
    public void run(){
        while (running){
            /*doing stuff*/
        }
    }
    public void pause(){
        running = false;
        try{
            thread.join();
        }catch (InterruptedException e){
            e.fillInStackTrace();
        }
    }
    public void resume(){
        running = true;
        thread = new Thread(this);
        thread.start();
    }
}

标签: androidsurfaceviewrunnablecustom-view

解决方案


推荐阅读