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);
}

假设页面中的控件比較多。就会有非常多的类型转换,这么搞下去还能不能在Android上愉快地开发项目了? 而使用ViewFinder则免去了类型转换,ViewFinder是一个在一个布局中找某个子控件的工具类,用户须要在使用时调用ViewFinder.initContentView函数来初始化ContentView,參数为Context和布局id。然后使用ViewFinder.findViewById来获取须要的view,返回的view则直接是你接收的类型,而不须要进行强制类型转换。

示比例如以下 :

@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<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."); } } /** * @return */ public static View getContentView() { return mContentView; } /** * @param viewId * @return */ @SuppressWarnings("unchecked") 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); } }

原文地址:https://www.cnblogs.com/yjbjingcha/p/6921076.html