Android中巧妙运用反射和注解,同时控制所有同类控件

来源:互联网 发布:js改变radio值 编辑:程序博客网 时间:2024/06/05 01:29
   讲到反射和注解我也是一知半解,但是俗话说得好,熟能生巧,在我多番应用和实践中掌握了一些技巧和大家分享一下。   比如大家需要实现一下同时控制当前Activity所有EditText的可编辑属性或者是控制所有的Button的可点击属性等等。就好像大家用QQ点击编辑按钮之后,才可以修改信息,不点击就只能看个人信息,而不能修改一样的情况。   EditText的可编辑属性可以通过xml文件中editable="true"来实现,当然也可以通过java代码来实现,但是这时候就需要两个属性配合使用:setFocusableInTouchMode(true)以及requestFocus() 来实现可以编辑,而如果想要设置为不可编辑,就需要:setFocusableInTouchMode(false)以及clearFocus()这两个属性实现。   而Button的是否可点击直接用属性setEnabled(flag)  flag 为 boolean类型

下面这段代码仅仅是操作同类控件的形同属性的方法,实现注解的方法
在我的另外一篇博客(讲解如何使用注解和反射实现绑定控件)中有用到。
自己学着写一个BindView来减少findViewById的应用

public void setAllEditTextEditableState(boolean isEditable,Activity act){    View rootView = act.getWindow().getDecorView();  //DecorView为整个Window界面的最顶层View    int fieldsCount = fields.length();    for(int i=0;i<fieldsCount;i++){        Field field = fields[i];        BindView bindView = field.getAnnotation(BindView.class);        if(bindView!=null){            int view_id = bindView.id();    //得到当前空间的id            field.setAccessible(true);      //当前为私有变量,私有变量不可直接调用,该方法使私有可用            View view = rootView.findViewById(view_id);            if(view instanceof EditText){    //EditText 当然也可以变成Button,这里以EditText为例                if(isEditable){                  view.setFocusableInTouchMode(isEditable);                  view.requestFocus();                }else{                  view.setFocusableInTouchMode(isEditable);                  view.clearFocus();                }            }else if(view instanceof Botton){                if(isEditable){                    view.setEnable(isEditable);                    view.setAlpha(0.88f);    //设置透明度,是的空间整体变稍灰                }else{                    view.setEnable(isEditable);                    view.setAlpha(1);                }            }            try{                 field.set(act,view);            }catch(IllegalAccessException e){            }        }    }}
原创粉丝点击