在我的自定义Android View中添加自定义字符串属性

5

我有一个派生自TableLayout的自定义视图,并且我需要声明一个字符串属性Title,就像这样:

<com.mycompany.controls.NavigationControllerView
xmlns:app="http://schemas.usetech.com/apk/res/onroad"
title="@string/nav_title"
...
/>

(能够通过资源引用指定值)。我已经在 values/attrs.xml 文件中指定了该属性:

<declare-styleable name="NavigationControllerView">
    <attr name="title" format="string"/>
    ...
</declare-styleable>

我的代码中我正在尝试:

public class NavigationControllerView extends TableLayout {
public NavigationControllerView(Context context, AttributeSet attrs) {
    super(context, attrs);
    View.inflate(getContext(), R.layout.inc_header, this);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.NavigationControllerView);
    CharSequence title = a.getString(R.styleable.NavigationControllerView_title);
    if (title != null)
        setTitle(title.toString());
}
...

但是没有运气,标题总是空的。你看到我错在哪里了吗?

1个回答

2

你应该使用

<com.mycompany.controls.NavigationControllerView
    xmlns:app="http://schemas.android.com/apk/res/onroad" 
    app:title="@string/nav_title" 
... /> 

不要错过app:前缀。还应使用正确的命名空间URI。

哎呀,你说得对,但即使使用应用程序前缀,标题也为空,既没有指定资源引用,也没有提供直接字符串值。 - ZlobnyiSerg
也许您正在使用错误的自定义命名空间?我使用xmlns:app =“http://schemas.android.com/apk/res/'packagepath'”,其中'packagepath'是根包路径。 - woodshy
好的!谢谢,schema 应该是这样的形式:http://schemas.android.com/apk/res/com.mycompany.myapp 请在你的答案中修复 xmlns:app,我会标记它为正确的。 - ZlobnyiSerg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接