我正在构建一个自定义视图,该视图需要将Class <>对象作为实体的属性之一。当我通过为它添加一个Setter使它以编程方式工作时,我想知道是否还有什么好方法可以将其添加到布局的XML中?
对于样式为“ class”的样式,似乎没有格式选项。我可以使用String,但是随后我不得不赌博该值实际上是一个有效的Class,并且我会丢失类型提示,因此它不是理想的选择。
有什么好的方法可以完成这项工作,还是我应该坚持以编程方式进行设置?
通用CustomView:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
活动:
//unsafe cast!
CustomView<String> customViewGeneric = (CustomView<String>) findViewById(R.id.customView);
customViewGeneric.addTypedValue("Test");
String test = customViewGeneric.getTypedValue(0);
Run Code Online (Sandbox Code Playgroud)
XML:
<org.neotech.test.CustomView
android:id="@+id/customView"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
Run Code Online (Sandbox Code Playgroud)
此方法使用通用的CustomView。对于将在xml中使用的每种类型,您都需要创建一个特定的类。
我添加了一个示例实现:
通用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);
}
}
Run Code Online (Sandbox Code Playgroud)
String类型的XML充气视图:
public class CustomViewString extends CustomView<String> {
//ADD Constructors!
}
Run Code Online (Sandbox Code Playgroud)
用于Integer类型的XML充气式视图:
public class CustomViewInteger extends CustomView<Integer> {
//ADD Constructors!
}
Run Code Online (Sandbox Code Playgroud)
活动:
CustomViewString customViewString = (CustomViewString) findViewById(R.id.customViewString);
CustomView<String> customViewGeneric = customViewString;
Run Code Online (Sandbox Code Playgroud)
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" />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
914 次 |
| 最近记录: |