Android findViewById使用技巧

原创
2016/11/25 21:56
阅读数 1.2W
程序中初始化控件方法:(View)findViewById(int redID),而且还得强制转化为相应类型,code浪费大量的时间,
阅读起来也不美观。
//一般写法,很累跟强制转换似的,很难受这样写
tv_title_other = (TextView) findViewById(R.id.tv_title_other);
//替代方式
protected <T extends View> T findView(int viewId) {
     return (T) findViewById(viewId);
} 
//简化之后
tv_title_other = findView(R.id.tv_title_other);

代码片段

ViewGroup.java {
    
    public ViewGroup(Context context, AttributeSet attrs) {
        super((Context)null, (AttributeSet)null, 0, 0);
        throw new RuntimeException("Stub!");
    }
}

View.java {

    public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        throw new RuntimeException("Stub!");
    }
}

 

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部