這樣開發Android好輕鬆哦

最近突發奇想,每次new 一個AndroidProject之後就要開始繁瑣的佈局,找控件啊,先要定義控件,然後findViewById之後,開始賦值啊,什麼的,那麼煩的一套完成之後代碼已經很多行了,我就在想可不可以簡化一下那?有的說用框架,最近那麼流行的幾大android框架可以註解啊什麼的,很輕鬆的就實現了,可是你們只知道用它,不知道怎麼實現的,那麼問題來了,如何自己寫一個那,很簡單。。。。。話不多說,直接上代碼!!!!!!!
這裏面就用到了一個接口,一個工具類,放在自己的項目當中,直接調用就好了,不用再導包什麼的。。。。

/**
 * 
 * @author thinkwyp
 * 
 */

public class MainActivity extends Activity {
    //這裏對應的xml裏面控件的id
    @CreateView(value = "text1")
    //這是與上面對應的控件類型
    private TextView text1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
        //只需要這麼一句話就可以輕鬆的實現控件的尋找
            Utils.injectObject(this, this,R.id.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //後面只管對控件進行操作了
       text1.setText("哈哈還不行啊");
    }
}

這是主的activity,裏面用到的@CreateView其實是一個接口,上代碼

/**
 * 
 * @author thinkwyp
 * 
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CreateView {
    String value();
}

這個接口就是這麼簡單。。。。。。
然後具體的實現還是在後面這個工具類中,直接上代碼,請注意。。

/**
 * 
 * @author thinkwyp
 * 
 */
public class Utils {
    public static void injectObject(Object obj, Activity activity, Class idClass)
            throws Exception {
        Class<?> classType = obj.getClass();
        Field[] fields = classType.getDeclaredFields();
        for (int i = 0; fields != null && i < fields.length; i++) {
            Field field = fields[i];
            if (field.isAnnotationPresent(CreateView.class)) {
                CreateView annotation = field.getAnnotation(CreateView.class);
                String name = annotation.value();
                if (TextUtils.isEmpty(name)) {
                    continue;
                }
                int id = findId(name, idClass);
                if (id <= 0) {
                    continue;
                }
                View v = activity.findViewById(id);
                if (v != null) {
                    field.setAccessible(true);
                    field.set(obj, v);
                }
            }
        }
    }
    public static int findId(String idName, Class r)
            throws IllegalArgumentException, IllegalAccessException {
        Class c = r;
        Field[] fields = c.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            String name = field.getName();
            if (name.equalsIgnoreCase(idName)) {
                int id = field.getInt(name);
                return id;
            }
        }

        return 0;
    }
}

這個工具類實現可能有點複雜,但是還是可以接受的。。。
開發android好輕鬆第一課就這樣結束了。。。。多多關注,以後會有更多的,嘿嘿

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章