我正在构建一个自定义 View ,它需要一个实体的 Class<> 对象作为其属性之一。虽然我通过为它添加一个 Setter 使其以编程方式工作,但我想知道是否有任何好的方法允许将它也添加到布局的 XML 中?
对于类型为“class”的样式,似乎没有格式选项。我可以使用字符串,但我不得不赌这个值实际上是一个有效的类,而且我会失去类型提示,所以它不是理想的。
有什么好的方法可以让它工作,还是我应该坚持以编程方式设置它?
最佳答案
方法一(带警告):
通用自定义 View :
public class CustomView<T> extends View {
private List<T> typedList = new ArrayList<T>();
public CustomView(Context context) {
this(context, null);
}
public CustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void addTypedValue(T object){
typedList.add(object);
}
public T getTypedValue(int position){
return typedList.get(position);
}
}
Activity :
//unsafe cast!
CustomView<String> customViewGeneric = (CustomView<String>) findViewById(R.id.customView);
customViewGeneric.addTypedValue("Test");
String test = customViewGeneric.getTypedValue(0);
XML:
<org.neotech.test.CustomView
android:id="@+id/customView"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
方法 2(无警告,安全!):
此方法使用通用 CustomView。对于将在 xml 中使用的每种类型,您需要创建一个特定的类。
我添加了一个示例实现:
Generic CustomView:(不要在 xml 中扩充这个):
public class CustomView<T> extends View {
private List<T> typedList = new ArrayList<T>();
public CustomView(Context context) {
this(context, null);
}
public CustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void addTypedValue(T object){
typedList.add(object);
}
public T getTypedValue(int position){
return typedList.get(position);
}
}
String 类型的 XML 充气 View :
public class CustomViewString extends CustomView<String> {
//ADD Constructors!
}
整数类型的 XML 充气 View :
public class CustomViewInteger extends CustomView<Integer> {
//ADD Constructors!
}
Activity :
CustomViewString customViewString = (CustomViewString) findViewById(R.id.customViewString);
CustomView<String> customViewGeneric = customViewString;
XML:
<org.neotech.test.CustomViewString
android:id="@+id/customViewString"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<org.neotech.test.CustomViewInteger
android:id="@+id/customViewInteger"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
关于android - 可以在 Android Layout XML 中传递一个 Class<> 对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27038394/