今天給大家分享一下簡化findViewById的寫法,
大家在寫代碼的時候可能煩透了寫 findViewById, 當然我們也可以利用相關注解框架來簡寫,比如ViewInject 去簡化這個操作。
至於用ViewInject性能方面,這裏不做介紹。
自定義一個ViewUtil類
public class ViewUtil {
/**
* activity.findViewById()
* @param context
* @param id
* @return
*/
public static <T extends View> T findViewById(Activity context, int id){
return (T) context.findViewById(id);
}
/**
* rootView.findViewById()
* @param rootView
* @param id
* @return
*/
public static <T extends View> T findViewById(View rootView, int id) { return (T) rootView.findViewById(id);
}
}
使用
TextView textView = ViewUtil.findViewById(this, R.id.textView);
ImageView imageView = ViewUtil.findViewById(convertView, R.id.image);
這樣利用了java泛型方法的類型推導特點,好處
1. 簡化了`findViewById寫法
2. 沒有了會增加代碼長度的類型轉化。
這樣就ok了。
如果我們想隱藏多個控件
可以在ViewUtil類中加上hide方法
/**
* 隱藏控件
*
* @param activity
* @param resourdId
*/
public static void hide(Activity activity, int... resourdIds) {
for (int id : resourdIds) {
View view = activity.findViewById(id);
if (view != null) {
view.setVisibility(View.GONE);
}
}
}
public static void hide(View parent, int... resourdIds) {
for (int id : resourdIds) {
View view = parent.findViewById(id);
if (view != null) {
view.setVisibility(View.GONE);
}
}
}
如果想顯示,編寫show方法
public static void show(Activity activity, int... resourdIds) {
for (int id : resourdIds) {
View view = activity.findViewById(id);
if (view != null) {
view.setVisibility(View.VISIBLE);
}
}
}
賦值方法:
public static void setText(Activity activity,int textViewId,String text){
if(activity ==null) return;
TextView textView = (TextView)activity.findViewById(textViewId);
if (textView!=null){
setText(textView,text);
}
}
public static void setText(TextView textView,String text){
textView.setText(text);
}
獲取值方法:
public static String getText(TextView view) {
return view.getText().toString();
}
public static String getText(Activity activity, int viewId) {
return getText((TextView) activity.findViewById(viewId));
}
其他改變背景,設置輸入狀態,清除等相關方法寫在ViewUtil類中,如需具體源碼,請回復ViewUtil獲取,或者回復工具類