嗨,我确信这很简单,只是让我不知所措: - )
我正在编写一个简单的帮助类,以便能够检查Field数组中提供的值,字段表示它们是EditText Widgets,这是正确的,我想要做的是能够访问输入的输入值进入EditText字段,请帮忙吗?
Field[] fields = clazz.getFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Required.class)) {
Log.d(TestClass.class.getName(), field.toString());
}
}
提前致谢
更新为QUESTION完整代码
package com.mobiqube.annotations;
import java.lang.reflect.Field;
import android.util.Log;
import android.widget.EditText;
public class EditTextValidator {
public EditTextValidator() {
}
public Boolean validate(Class clazz) throws IllegalArgumentException, IllegalAccessException{
Boolean isValid = true;
Field[] fields = clazz.getFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Required.class)) {
Log.d(EditTextValidator.class.getName(), field.toString());
if(field instanceof EditText){
EditText editText = (EditText)field ;
String txt=editText.getText().toString();
Log.d(EditTextValidator.class.getName(), txt);
}
}
}
return isValid;
}
public String getMessage(){
String returnStr = "";
return returnStr;
}
}
错误现在
if(field instanceof EditText){ //
和 EditText editText =(EditText)字段;
答案 0 :(得分:2)
假设您有clazz类型的对象:
MyClass object = <something>
// clazz represent the class of this object
Class<?> clazz = object.getClass();
// Note that it can also be obtained by MyClass.class
// fields represent the members of MyClass
Field[] fields = clazz.getFields();
for (Field field : fields) {
// field is a member of MyClass
// To get the class of this member :
Class<?> c = field.getType();
// To get the value of the member in the object: (object is an instance of MyClass)
Object o = field.get(object);
// If you want to know if the field represent an EditText or a derived class :
if (EditText.class.isAssignableFrom(c)) {
EditText value = (EditText) field.get(object);
}
}
关于你的问题,你需要你试图验证的对象,因为类本身是不够的(除非你只是验证静态字段?)
答案 1 :(得分:1)
试试这个:
EditText[] fields = clazz.getFields();
for (EditText field : fields) {
Log.e("result",field.getText().toString());
}
答案 2 :(得分:0)
您好,您可以使用以下代码
if(field instanceof EditText){
EditText editText = (EditText)field ;
String txt=editText.getText().toString();
}
答案 3 :(得分:0)
AppCompatActivity activity=(AppCompatActivity)
Field id = R.id.class.getDeclaredField(field.getName());
EditText et= (EditText)activity.findViewById(id.getInt(id));
//or
AppCompatActivity activity=(AppCompatActivity)
EditText et= (EditText)activity.findViewById(id);