Die*_*art 7 android custom-controls attr
我一直在为Android的自定义控件工作,虽然我试图做这里建议的东西似乎有些事我做错了.
这是我的代码,看看是否有人可以发现问题:
MyComponent.java
public MyComponent(Context context, AttributeSet attrs)
{
super(context);
TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.MyComponent);
CharSequence myId = arr.getString(R.styleable.MyComponent_identifier);
if (myId != null)
{
this.setIdentifier(myId.toString());
}
Integer cds = arr.getInteger(R.styleable.MyComponent_cd_number, 0);
if(cds != null)
{
this.setCds(cds);
}
arr.recycle();
}
Run Code Online (Sandbox Code Playgroud)
attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyComponent">
<attr name="cd_number" format="integer" />
<attr name="identifier" format="string" />
</declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)
main.xml中
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:bgl="http://schemas.android.com/apk/res/my.test.package.components"
android:id="@+id/table"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
<my.test.package.MyComponent
android:id="@+id/hand"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2"
bgl:cd_number="4"
bgl:identifier="plr"/>
...
</TableLayout>
Run Code Online (Sandbox Code Playgroud)
当我把它我得到以下错误:
错误:未发现在包"my.test.package"错误属性"cd_number"资源标识符:没有在包"my.test.package"找到的属性"识别符"资源标识符
如果我将命名空间更改为:
xmlns:bgl="http://schemas.mywhatever.com/apk/res/my.test.package"
Run Code Online (Sandbox Code Playgroud)
...错误发生并且事情运行但myId为null并且cds为0(默认值!)返回MyComponent.java构造函数.
我说这是一个非常基本的错误,但我无法发现它,因为没有太多的文件,我决定在这里问.
提前致谢!
Die*_*art 15
好.我解决了!
在原帖上我有:
xmlns:bgl="http://schemas.android.com/apk/res/my.test.package
Run Code Online (Sandbox Code Playgroud)
......但在我的来源中,我有:
xmlns:bgl="http://schemas.android.com/apk/res/my.test.package.components
Run Code Online (Sandbox Code Playgroud)
...因为我认为应该将URI放到组件包中.
这是错的!
在xmlns上它应该是在Manifest上声明的应用程序名称!
当我删除xmlns的"组件"部分时,它"匹配"了Manifest中的应用程序名称,错误就消失了,当我在调试中运行该东西时,我实际上可以看到我传递给XML中的参数的值!
希望这有助于其他人!:-)
UPDATE
后来我需要将控件移动到库中并再次遇到问题.看来,当您将组件放在库中并在客户端应用程序上使用它时,您必须声明xmlns,如下所示:
xmlns:myns="http://schemas.android.com/apk/res-auto"
Run Code Online (Sandbox Code Playgroud)
如果你这样做(并将库声明为Android依赖项)Eclipse(或者它是Android?)将搜索依赖项以获取适当的属性绑定.
归档时间: |
|
查看次数: |
3229 次 |
最近记录: |