Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
905 views
in Technique[技术] by (71.8m points)

android - get Activity object while in View context

This is a followup to this post:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...