在我的自定义android视图中添加自定义字符串属性

Zlo*_*erg 5 android android-layout

我有一个从TableLayout派生的视图视图,我需要声明String属性Title,如下所示:

<com.mycompany.controls.NavigationControllerView
xmlns:app="http://schemas.usetech.com/apk/res/onroad"
title="@string/nav_title"
...
/>
Run Code Online (Sandbox Code Playgroud)

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

<declare-styleable name="NavigationControllerView">
    <attr name="title" format="string"/>
    ...
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我正在尝试:

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

但没有运气,标题始终为空。看到我错了吗?

woo*_*shy 2

你应该使用

<com.mycompany.controls.NavigationControllerView
    xmlns:app="http://schemas.android.com/apk/res/onroad" 
    app:title="@string/nav_title" 
... /> 
Run Code Online (Sandbox Code Playgroud)

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