tags:

views:

59

answers:

1

This is a followup to this post:

http://stackoverflow.com/questions/3897176/findviewbyid-in-a-subclassed-surfaceview-throwing-runtimeexception

Based on Romain Guy's feedback (which I'll accept shortly as it is a solution), I'd like to obtain the calling Activity from within the View, so that I can use it to obtain the desired TextView resource.

I don't see any methods in View that return Activity. What is the proper way to do this? Or is there a better alternative for working with TextViews from within another View context.

Basically, I am calling setContentView(R.layout.xxx) in onCreate() (as usual), so I don't really have a way to pass in references to additional TextViews unless I awkwardly retrieve the View after setContentView and then make calls on it.

+1  A: 

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.

Romain Guy
Thanks. It "feels" awkward to do it that way, but I guess it is the Android Way(tm). I'll probably do it like: MySurfaceView v = findViewById(R.id.something); setContentView(v); v.setContent(findViewById(R.id.content)); to make it less awkward.
dpk
You can't do a findViewById() before calling setContentView().
Romain Guy
Quite right. What a weird, weird arrangement, to have to identify an object, set it on another object, and ask that other object for a copy of it again, and to not allow for subordinate views within views. I think what I'm facing here is that the Android API is fundamentally different than anything I would have designed. Anyway, thank you. The code is working as expected now.
dpk
What do you mean by "ask that other object for a copy of it again"? You definitely don't need to do it. And Views (well ViewGroups) can contain children Views, there's no problem with that. It just happens that SurfaceView is *not* a ViewGroup.
Romain Guy