android通过泛型获取控件或视图

 1     @SuppressWarnings("unchecked")
 2     public <T extends Fragment> T getFragment(int id) {
 3         T result = (T)getFragmentManager().findFragmentById(id);
 4         if (result == null) {
 5             throw new IllegalArgumentException("fragment 0x" + Integer.toHexString(id)
 6                     + " doesn't exist");
 7         }
 8         return result;
 9     }
10 
11     /**
12      * Convenient version of {@link #findViewById(int)}, which throws
13      * an exception if the view doesn't exist.
14      */
15     @SuppressWarnings("unchecked")
16     public <T extends View> T getView(int id) {
17         T result = (T)findViewById(id);
18         if (result == null) {
19             throw new IllegalArgumentException("view 0x" + Integer.toHexString(id)
20                     + " doesn't exist");
21         }
22         return result;
23     }

 

posted @ 2015-12-05 15:18  木木小强  阅读(313)  评论(0编辑  收藏  举报