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

Emi*_*ile 49 android components custom-attributes uicomponents

在android中创建自定义组件时,经常会询问如何创建并将attrs属性传递给构造函数.

通常建议在java中创建一个只使用默认构造函数的组件,即

new MyComponent(context);
Run Code Online (Sandbox Code Playgroud)

而不是试图创建一个attrs对象来传递给经常在基于xml的自定义组件中看到的重载构造函数.我试图创建一个attrs对象,它似乎不容易或根本不可能(没有非常复杂的过程),并且所有帐户都不是真正需要的.

那么我的问题是:在java中构造自定义组件的最有效方法是什么,它传递或设置在使用xml对组件进行膨胀时由attrs对象设置的属性?

Blr*_*rfl 95

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

您可以创建超出三个标准的构造函数,从中View添加您想要的属性...

MyComponent(Context context, String foo)
{
  super(context);
  // Do something with foo
}
Run Code Online (Sandbox Code Playgroud)

......但我不推荐它.遵循与其他组件相同的约定更好.这将使您的组件尽可能灵活,并防止使用您的组件的开发人员撕掉他们的头发因为您的组件与其他所有内容不一致:

1.为每个属性提供getter和setter:

public void setFoo(String new_foo) { ... }
public String getFoo() { ... }
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

完成所有这些后,您可以以MyCompnent编程方式实例化...

MyComponent c = new MyComponent(context);
c.setFoo("Bar");
Run Code Online (Sandbox Code Playgroud)

......或通过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>
Run Code Online (Sandbox Code Playgroud)

其他资源 - https://developer.android.com/training/custom-views/create-view