设为首页 加入收藏

TOP

Android解决使用findViewById时需要对返回值进行类型转换问题的辅助类
2014-11-23 21:31:40 来源: 作者: 【 】 浏览:9
Tags:Android 解决 使用 findViewById 需要 返回 进行 类型 转换 问题 辅助

在我们的开发工作时,findViewById可能是用得最多的函数之一,但它特别讨厌的地方就是我们经常需要对返回的view进行类型转换,输入麻烦、代码丑陋,例如以前我们在Activity中找一些子控件一般是这样 :


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 查找子控件
TextView textView = (TextView)findViewById(R.id.my_textview);
ImageView imageView = (ImageView)findViewById(R.id.my_imageview);
ListView listView = (ListView)findViewById(R.id.my_listview);
}


示例如下 :


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化
ViewFinder.initContentView(this, R.layout.activity_main) ;
// 查找子控件
TextView textView = ViewFinder.findViewById(R.id.my_textview);
ImageView imageView = ViewFinder.findViewById(R.id.my_imageview);
ListView listView = ViewFinder.findViewById(R.id.my_listview);
}


ViewFinder的实现


/**
* view finder, 方便查找View。用户需要在使用时调用initContentView,
* 将Context和布局id传进来,然后使用findViewById来获取需要的view
* ,findViewById为泛型方法,返回的view则直接是你接收的类型,而不需要进行强制类型转换.比如,
* 以前我们在Activity中找一个TextView一般是这样 :
* TextView textView = (TextView)findViewById(viewId);
* 如果页面中的控件比较多,就会有很多的类型转换,而使用ViewFinder则免去了类型转换,
* 示例如下 :
* TextView textView = ViewFinder.findViewById(viewId);
*
* @author mrsimple
*/
public final class ViewFinder {


/**
* LayoutInflater
*/
static LayoutInflater mInflater;


/**
* 每项的View的sub view Map
*/
private static SparseArray mViewMap = new SparseArray();


/**
* Content View
*/
static View mContentView;


/**
* 初始化ViewFinder, 实际上是获取到该页面的ContentView.
*
* @param context
* @param layoutId
*/
public static void initContentView(Context context, int layoutId) {
mInflater = LayoutInflater.from(context);
mContentView = mInflater.inflate(layoutId, null, false);
if (mInflater == null || mContentView == null) {
throw new RuntimeException(
"ViewFinder init failed, mInflater == null || mContentView == null.");
}
}


/**
* @return
*/
public static View getContentView() {
return mContentView;
}


/**
* @param viewId
* @return
*/
@SuppressWarnings("unchecked")
public static T findViewById(int viewId) {
// 先从view map中查找,如果有的缓存的话直接使用,否则再从mContentView中找
View tagetView = mViewMap.get(viewId);
if (tagetView == null) {
tagetView = mContentView.findViewById(viewId);
mViewMap.put(viewId, tagetView);
}
return tagetView == null null : (T) mContentView.findViewById(viewId);
}
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Android Touch事件分发过程 下一篇Objective-C中的Block(块)详解

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: