(完全公开:此问题是创建自定义视图的分支)
您可以创建从MyCompnent继承的三个标准构造函数,这些构造函数可以添加所需的属性...
MyComponent(Context context, String foo)
{
super(context);
// Do something with foo
}
...但是我不建议这样做。 最好遵循与其他组件相同的约定。 这将使您的组件尽可能地灵活,并且将防止使用您的组件的开发人员将头发撕裂,因为您的组件与其他所有组件都不一致:
1.为每个属性提供获取器和设置器:
public void setFoo(String new_foo) { ... }
public String getFoo() { ... }
2.在MyCompnent中定义属性,以便可以在XML中使用它们。
3.提供MyCompnent中的三个标准构造函数。
如果您需要从采用MyCompnent的构造函数之一的属性中挑选任何东西,则可以...
TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.MyComponent);
CharSequence foo_cs = arr.getString(R.styleable.MyComponent_foo);
if (foo_cs != null) {
// Do something with foo_cs.toString()
}
arr.recycle(); // Do this when done.
完成所有这些后,您可以以编程方式实例化MyCompnent ...
MyComponent c = new MyComponent(context);
c.setFoo("Bar");
...或通过XML:
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:blrfl="http://schemas.android.com/apk/res-auto"
...etc...
>
android:id="@+id/customid"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
blrfl:foo="bar"
blrfl:quux="bletch"
/>
其他资源-[https://developer.android.com/training/custom-views/create-view]