get Activity object while in View context

前端 未结 2 1960
醉梦人生
醉梦人生 2021-01-14 16:37

This is a followup to this post:

findViewById in a subclassed SurfaceView throwing RuntimeException

Based on Romain Guy\'s feedback (which I\'ll accept short

2条回答
  •  花落未央
    2021-01-14 17:10

    An Activity is a Context, but there is no guarantee that the Context used by a View is always an Activity. Getting the views from onCreate() to do some setup is perfectly valid and is how Android applications are usually written. You could do something like this for instance:

    setContentView(...);
    MySurfaceView v = findViewById(R.id.theusrface);
    TextView t = findViewById(R.id.thecontent);
    v.setContent(v);
    

    The logic should not go in your Views.

提交回复
热议问题