我们常用
Intent intent = new Intent(this, AnnotationActivity.class);
intent.putExtra("name", "tony");
intent.putExtra("age", 30);
.this.startActivity(intent);
来传递参数
通过
Intent intent = getIntent();
String name = intent.getStringExtra("name");
int age = intent.getIntExtra("age", 0);
来获取传递过来的参数
今天我们自己定义一个注解轻松接收数据,特别是数据很多时候:
IntentParam
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface IntentParam {
String value() default "";
}
AnnotationActivity
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.example.demozhong.R;
public class AnnotationActivity extends AppCompatActivity {
@IntentParam("name")
String nameFri;
@IntentParam()
int age;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_annotation);
InjectIntentParamUtil.init(this);
Log.w("AnnotationActivity : ","-------------------name : "+nameFri+" age : "+ this.age);
}
}
InjectIntentParamUtil
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import java.lang.reflect.Field;
public class InjectIntentParamUtil {
public static void init(Activity activity) {
Intent intent = activity.getIntent();
Class<? extends Activity> aClass = activity.getClass();
Field[] declaredFields = aClass.getDeclaredFields();
for (Field declaredField : declaredFields) {
if (declaredField.isAnnotationPresent(IntentParam.class)) {
IntentParam annotation = declaredField.getAnnotation(IntentParam.class);
Class<?> type = declaredField.getType();
if (type.equals(String.class)) {
String stringExtra;
if (annotation.value().isEmpty()) {
stringExtra = intent.getStringExtra(declaredField.getName());
} else {
stringExtra = intent.getStringExtra(annotation.value());
}
declaredField.setAccessible(true);
try {
declaredField.set(activity, stringExtra);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else if (type.equals(int.class)) {
int intExtra=0;
if (annotation.value().isEmpty()) {
intExtra = intent.getIntExtra(declaredField.getName(),0);
} else {
intExtra = intent.getIntExtra(annotation.value(),0);
}
declaredField.setAccessible(true);
try {
declaredField.set(activity, intExtra);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else if (type.equals(float.class)) {
...
}else
...
}
}
}
}