init View via reflection - Android User Interface

Android examples for User Interface:View

Description

init View via reflection

Demo Code


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.Activity;
import android.view.View;

public class Main{
    public static void initView(Activity activity) {
        Class<? extends Activity> cls = activity.getClass();
        try {//  w  w  w. jav  a2s  .  c o  m
            Field[] fields = cls.getDeclaredFields();
            Method method = cls.getMethod("findViewById",
                    new Class[] { int.class });
            for (Field field : fields) {
                Class type = field.getType();
                if (View.class.isAssignableFrom(type)) {
                    Class idCls = R.id.class;
                    Field idField = idCls.getDeclaredField(field.getName());

                    Object args = idField.get(idField);
                    Object value = method.invoke(activity,
                            new Object[] { args });
                    field.setAccessible(true);
                    field.set(activity, value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Related Tutorials