java xml 组件_android-如何在java和xml中传递自定义组件参数

(完全公开:此问题是创建自定义视图的分支)

您可以创建从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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值