简化你的findViewById

2016-01-29  本文已影响63人  熊凯

不需要ViewInject,简化你的findViewById,viewinject

这时,我就想着自己去实现一下简化findViewById,简化后怎么用呢?看下面的代码,

TextView textView = V.f(this, R.id.textView);
ImageView imageView = V.f(convertView, R.id.image);

这种方式解决了两个问题,

  1. 简化了findViewById 这个长长的方法。
  2. 没有了会增加代码长度的类型转化。
    那我们应该怎么去实现这两个V.f 方法呢?其实很简单。
/**
 * view utils
 * @author loader
 *
 */
public class V {

    /**
     * activity.findViewById()
     * @param context
     * @param id
     * @return
     */
    public static <T extends View> T f(Activity context, int id) {
        return (T) context.findViewById(id);
    }

    /**
     * rootView.findViewById()
     * @param rootView
     * @param id
     * @return
     */
    public static <T extends View> T f(View rootView, int id) {
        return (T) rootView.findViewById(id);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读