开发者

When is casting Context to Activity allowed?

开发者 https://www.devze.com 2023-03-06 23:42 出处:网络
In a showAlret(String message, Context ctx) method of an alert Dialog class, I am trying to get a reference to TextView in the dialog\'s layout XML:

In a showAlret(String message, Context ctx) method of an alert Dialog class, I am trying to get a reference to TextView in the dialog's layout XML:

TextView tv = (TextView)((MyA开发者_Go百科ctivity)ctx).findViewById(R.id.tv_about);

Not before calling inflate() of course:

LayoutInflater li = LayoutInflater.from(ctx);
View view = li.inflate(R.layout.aboutdialog, null);

The problem is that this call returns tv as null.

Since the code compiles without any warnings, I am assuming that this is due to "illegal" casting of Context to MyActivity.

I have encountered quite a few cases in which casting Context to Activity is the only thing that really works, so why doesn't this work in this case?

When does casting Context to Activity make sense?

What are the "unspoken rules" in this regard?


LayoutInflater li = LayoutInflater.from(ctx);
View view = li.inflate(R.layout.aboutdialog, null);
TextView tv = view.findViewById(R.id.tv_about);

I understand that your textview is a part of the dialog xml so, you need to findViewById() on the dialogs view instead of the activity.


No it isn't otherwise you would have exception. Are you sure that your Activity hs loaded the TextView from xml at the moment you try to get it?


I found the solution. My mistake was that I was doing:

TextView tv = (TextView)((MyActivity)ctx).findViewById(R.id.tv_about);

Instead of:

TextView tv = (TextView)view.findViewById(R.id.tv_about);


On a side not, you can cast the context to an Activity when it is an Activity. Context is a base class for Activity.

You should only have to cast to an Activity when your method is not available on the Context object. Casting is just a way to tell the compiler that you are sure that it is an Activity therfore the compiler will asume you know what you are doing.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号