1.android中findViewById需要对返回值强制类型转换的问题描述
findViewById的返回值是view类型,通常开发中,我们需要将其强制转换成实际类型,输入麻烦、代码丑陋:
@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);
}
2.Android解决使用findViewById时需要对返回值进行类型转换问题的辅助类ViewFinder
ViewFinder类的核心是将view的id保存到SparseArray类型的mViewMap变量中,方便后面引用,还有就是类型转换。
import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
public final class ViewFinder {
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.");
}
}
public static View getContentView() {
return mContentView;
}
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);
}
}
3.ViewFinder类的使用
首先调用initContentView方法,将Context和布局id传进来,再调用ViewFinder.findViewById();方法获得对象。
@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);
}
4.参考资料: