【问题标题】:Create Custom Compound View in Android with Attributes在 Android 中使用属性创建自定义复合视图
【发布时间】:2014-03-11 15:40:33
【问题描述】:

我在库应用程序中创建了一个自定义复合视图,一切正常。当我添加自定义属性来查看时,我总是得到默认值。我关注this steps,只有一个区别:我的观点是在图书馆项目中。

/res/values/attrs.xml

<resources>
    <declare-styleable name="DatePickerView">
        <attr name="showToday" format="boolean" />
        <attr name="calendar" format="enum">
            <enum name="jalali" value="0" />
            <enum name="gregorian" value="1" />
        </attr>
    </declare-styleable>
</resources>

包含视图的布局文件:

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:farayan="http://schemas.android.com/apk/lib/net.farayan.android.view"
...
    <net.farayan.android.view.datepicker.DatePickerView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        farayan:showToday="false"
        farayan:calendar="gregorian"/>
...

组件代码:

int calendar;
boolean showToday;

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DatePickerView, 0, 0);
try {
    calendar = a.getInteger(R.styleable.DatePickerView_calendar, 0);
    showToday = a.getBoolean(R.styleable.DatePickerView_showToday, true);
} finally {
    a.recycle();
}

calendarshowToday 始终分别为 0true。有什么想法吗?

【问题讨论】:

    标签: android android-layout android-view android-custom-view


    【解决方案1】:

    这里好像有点不对:

        <RelativeLayout 
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:farayan="http://schemas.android.com/apk/lib/net.farayan.android.view"
    

    怎么改成:

            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:farayan="http://schemas.android.com/apk/res/net.farayan.android.view"
    

    net.farayan.android.view 是您的应用根命名空间。

    更新1

    xmlns:farayan="http://schemas.android.com/apk/res/your_main_app_package"

    Here 就是一个例子。它使用库项目中定义的视图。

    【讨论】:

    • net.farayan.android.view 是我在清单文件中声明的根包。
    • 正如我之前所说,我的视图是在附加到主应用程序的库应用程序中定义的。 attr.xml 也在库应用程序中定义。如果我在定义 xml 命名空间时将 lib 更改为 res,我会收到此错误:No resource identifier found for attribute 'calendar' in package
    • 您的代码是否在任何地方发布?我很欣赏你的方法(只是通过将 YEAR、MONTH、DAY 值更改为 Jalali 来更改原始日历的布局,所以一切都超越了 UI)
    • @AliBehzadianNejad,你的问题解决了吗?我正在研究一个图书馆项目并处理了同样的问题。我更新了答案。希望这会有所帮助。
    • @Xaqron 我正在做一个新版本,它还没有完成。完成后,我会将其发布到我的 GitHub (github.com/alibehzadian)
    【解决方案2】:

    如果我们在项目中添加新的复合视图代码及其属性,我们应该在布局的开头添加:

    xmlns:custom="http://schemas.android.com/apk/res/your_main_app_package
    

    如果新的复合视图位于链接到我们项目的库项目中,我们应该添加以下内容:

    xmlns:custom="http://schemas.android.com/apk/res-auto
    

    链接:https://stackoverflow.com/a/10217752/1152549

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 2012-07-25
      • 1970-01-01
      相关资源
      最近更新 更多