这是Annotation
类
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface InjectExtra {
public String value();
}
以下是处理Annotation
课程的课程:InjectActivity
:
public class InjectActivity extends Activity {
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handleAnnotation();
}
private void handleAnnotation(){
final Field[] fields = getClass().getDeclaredFields();
Bundle extras = getIntent().getExtras(); //TODO here always null!!why?
if(fields == null || fields.length <= 0 || extras == null) {
return;
}
for(final Field field : fields) {
if(field.isAnnotationPresent(InjectExtra.class)) {
field.setAccessible(true);
final InjectExtra injectExtra = field.<InjectExtra>
getAnnotation(InjectExtra.class);
field.set(object, extras.get(injectExtra.value()));
}
}
}
}
现在我正在尝试使用InjectActivity
:
public class SimpleActivity extends InjectActivity{
@InjectExtra("id")
private String id;
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
}
当我尝试开始此活动时,它不起作用:
Intent i = new Intent(currentActivity.this,SimpleActivity.class);
i.putExtra("id", "kai");
startActivity(i);
这是因为getIntent().getExtras()
中的InjectActivity
始终为null
。但是,当我将方法handleAnnotation
从InjectActivity
移动到SimpleActivity
时,它就可以了!
有人能帮助我吗?
答案 0 :(得分:0)
尝试替换代码的和平:
Intent i = new Intent(currentActivity.this,SimpleActivity.class);
i.putExtra("id", "kai");
startActivity(i);
这种代码安静:
Intent i = new Intent(currentActivity.this,SimpleActivity.class);
Bundle bundle = new Bundle();
bundle.putString("id", "kai");
i.putExtras(bundle);
startActivity(i)