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); }
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<View> mViewMap = new SparseArray<View>(); /** * 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 extends View> 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); } }
首先调用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); }
1.android中通过辅助类解决findViewById需要对返回值强制类型转换的问题
http://www.yee4.com/blog/857.html
2.Android应用性能优化之使用SparseArray替代HashMap
http://blog.csdn.net/buleriver/article/details/8478203