安卓:一个findViewById()方法返回我们并不需要转换值 [英] Android: a findViewById() method that returns values we don't need to cast

查看:255
本文介绍了安卓:一个findViewById()方法返回我们并不需要转换值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我已经厌倦了写转换运算符,每对 Activity.findViewById()返回原查看 ,我终于尝试的建议是由网络

As I'm tired of writing a cast operator for EVERY Activity.findViewById() that returns raw View, I finally tried one way that was suggested by Internet.

public abstract class MyActivity extends Activity {

    @SuppressWarnings("unchecked")
    protected <T extends View> T findViewByID(int id) {
        return (T) this.findViewById(id);
    }
}

注意这是不超载(最后一个D是大写)。编译器说,我们不能施放查看 T 。有什么毛病我实施?奇怪的是,这个建议几乎看不到的英文网站(例如,即使在我们可爱的堆栈溢出),以及例外是上面贴的部位。

Note this isn't overloaded (the last "D" is upper case). The compiler says we can't cast View into T. Is there anything wrong with my implementing? Strangely, this suggestion was hardly seen in English websites (e.g. even in our lovely Stack Overflow), and the exception was the site posted above.

推荐答案

这在我的测试项目工作正常。没有编译器错误:

This works fine in my test project. No compiler error:

这篇关于安卓:一个findViewById()方法返回我们并不需要转换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆