码迷,mamicode.com
首页 > 其他好文 > 详细

通过泛型来简化findViewById

时间:2015-01-28 00:52:38      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:

我们一般写findViewById都要加个强制转换,感觉很麻烦,现在你可以在你的BaseActivity中写入如下方法:

@SuppressWarnings(“unchecked”)
public final <E extends View> E getView (int id) {
    try {
        return (E) findViewById(id);
    } catch (ClassCastException ex) {
        Log.e(TAG, “Could not cast View to concrete class.”, ex);
        throw ex;
    }
}

之后你在你的代码中就可以通过getView来获得控件了。

举例:

TextView textView = getView(R.id.textview);
Button button = getView(R.id.button);
ImageView image = getView(R.id.imageview);
注意:如果级联调用getView 函数,则还是需要Cast的,如下示例:
private static void myMethod (ImageView img) {
    //Do nothing
}
@Override
public void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // myMethod(getView(R.id.imageview)); //这样无法通过编译
    myMethod((ImageView) getView(R.id.imageview)); //需要Cast才可以
}

 

其他的方法请参考:http://www.stormzhang.com/android/androidtips/2014/08/24/android-viewfinder/

 

通过泛型来简化findViewById

标签:

原文地址:http://www.cnblogs.com/tianzhijiexian/p/4254634.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!