[英]How to pass custom component parameters in java and xml
在android中創建自定義組件時,經常會詢問如何創建並將attrs屬性傳遞給構造函數。
通常建議在java中創建一個只使用默認構造函數的組件,即
new MyComponent(context);
而不是試圖創建一個attrs對象來傳遞給經常在基於xml的自定義組件中看到的重載構造函數。 我試圖創建一個attrs對象,它似乎不容易或根本不可能(沒有非常復雜的過程),並且所有帳戶都不是真正需要的。
那么我的問題是:在java中構造自定義組件的最有效方法是什么,它傳遞或設置在使用xml對組件進行膨脹時由attrs對象設置的屬性?
(完全披露:此問題是創建自定義視圖的分支)
您可以創建超出從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
編程方式實例化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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.