转载请注明出处:http://blog.youkuaiyun.com/guiping_ding/article/details/50614970
findViewById除了用注解或其他框架省略外的新技能。
在Activity中
可以把这个方法写在BaseActivity中,这样在所有的Activity中都可以省略findViewById的调用 直接 $(R.id.xx)
protected <T extends View> T $(int id) {
return (T) super.findViewById(id);
}
调用:
private TextView mShowWifiMessage_tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mShowWifiMessage_tv = $(R.id.show_wifiMessage);
}
在Fragment中
也是写在BaseFragment中,然后所有的Fragment继承BaseFragment,所有继承BaseFragment的控件只需要$(v,R.id.xx)就能搞定。
protected <T extends View> T $(View v, int id) {
return (T) v.findViewById(id);
}
在Fragment中调用:
private TextView showMessageTv;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
showMessageTv = $(v,R.id.show_wifiMessage);
return v;
}