(完全披露:这个问题是Creating custom view 的一个分支)
除了从View 继承的三个标准构造函数之外,您还可以创建添加所需属性的构造函数...
MyComponent(Context context, String foo)
{
super(context);
// Do something with foo
}
...但我不推荐它。最好遵循与其他组件相同的约定。这将使您的组件尽可能灵活,并防止使用您的组件的开发人员因为您的组件与其他所有内容不一致而撕毁他们的头发:
1.为每个属性提供 getter 和 setter:
public void setFoo(String new_foo) { ... }
public String getFoo() { ... }
2。在res/values/attrs.xml 中定义属性,以便它们可以在 XML 中使用。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyComponent">
<attr name="foo" format="string" />
</declare-styleable>
</resources>
3。提供来自View的三个标准构造函数。
如果您需要从采用AttributeSet 的构造函数之一的属性中挑选任何内容,您可以这样做...
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:
<!-- res/layout/MyActivity.xml -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:blrfl="http://schemas.android.com/apk/res-auto"
...etc...
>
<com.blrfl.MyComponent
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"
/>
</LinearLayout>
其他资源 - https://developer.android.com/training/custom-views/create-view