Android 反射获得控件对象

例:
 
  
	@ViewInject(R.id.pull_to_refresh_listview)
	private PullToRefreshListView pullToRefreshListView;
不再使用一下代码初始化
 
  
pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pullToRefreshListView);
 
  
实现方式(网上有很多代码):
一个interface和一个class
interface:
 
  
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by anykaa on 2015/6/3.
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ViewInject {
    int value();
}
class
import android.app.Activity;
import java.lang.reflect.Field;

/**
 * Created by anykaa on 2015/6/3.
 */
@SuppressWarnings("unused")
public class ViewInjectClass {
    public static void autoInjectAllField(Activity activity) {
        //得到Activity对应的Class
        Class clazz = activity.getClass();
        //得到该Activity的所有字段
        Field[] fields = clazz.getDeclaredFields();
        try {
            for (Field field : fields) {
                //判断字段是否标注InjectView
                if (field.isAnnotationPresent(ViewInject.class)) {
                    //如果标注了,就获得它的id
                    ViewInject inject = field.getAnnotation(ViewInject.class);
                    int id = inject.value();
                    if (id > 0) {
                        //反射访问私有成员,必须加上这句
                        field.setAccessible(true);
                        try {
                            //然后对这个属性复制
                            field.set(activity, activity.findViewById(id));
                        } catch (Exception ex) {
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

使用方式及建议:
统一写一个BaseActivity
 
  
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.anykaalibrary.ViewInjectClass;

/**
 * Created by anykaa on 15/12/30.
 */
public class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        ViewInjectClass.autoInjectAllField(this);
    }
}
使用
 
  
public class MainActivity extends BaseActivity {
    
    @ViewInject(R.id.pull_to_refresh_listview)
    private PullToRefreshListView pullToRefreshListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }
}


 其实我并不建议这样使用,我倒是希望开发工具能够根据类似这种代码,在编译前自动将代码改成 
  
	pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pullToRefreshListView);
这种形式。
 
  
特此梳理备用。

你可能感兴趣的:(Android)