使用自定义视图的自定义属性传递布局资源

时间:2013-07-19 11:11:29

标签: android xml layout view custom-controls

我想在XML中为自定义视图指定子布局,类似于include元素的layout属性:

<include layout="@layout/all_apps_cling"
         android:id="@+id/all_apps_cling"
         android:layout_width="match_parent"
         android:layout_height="match_parent"/>

此外,我需要在Eclipse或IntelliJ图形布局预览中的设计时自定义视图

使用attr name =“android:layout”不起作用

[至少不在图形布局预览中]

attrs.xml

<declare-styleable name="ShowcaseView">
    <attr name="android:layout"/>
</declare-styleable>

usecase.xml

<com.github.espiandev.showcaseview.ShowcaseView
    style="@style/ShowcaseView"/>

styles.xml

<style name="ShowcaseView" parent="match_fill">
    <item name="android:layout">@layout/handy</item>
</style>

ShowcaseView.java

public ShowcaseView(Context context) {
    this(context, null, R.styleable.CustomTheme_showcaseViewStyle);
}

public ShowcaseView(Context context, AttributeSet attrs) {
    this(context, attrs, R.styleable.CustomTheme_showcaseViewStyle);
}

public ShowcaseView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    // Get the attributes for the ShowcaseView
    final TypedArray styled = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ShowcaseView, 0, 0);
    TypedValue handLayout = null;
    // Not sure if should be using .getValue in the first place
    // But there is no method TypedValue.getLayout or such 
    if (styled.getValue(R.styleable.ShowcaseView_android_layout, handLayout)) {
        // Does not reach here
    } else {
        // Reaches here instead i.e. getValue failed
    }
    styled.recycle();
}

任何解决方案?

我无法使用<attr name="linkedLayout" format="reference"/>,因为我需要它在图形布局预览中工作 - 请参阅设计器Resources$NotFoundException in Graphical Layout ADT preview (but app actually Works)中访问资源的问题

1 个答案:

答案 0 :(得分:1)

尝试将布局放在主布局文件中:

<ShowcaseView ...>
    <include .../>
</ShowcaseView> 

当然你也可以直接添加孩子而不是包含标签:

<ShowcaseView ...>
    <Button .../>
    ...
    <Button .../>
</ShowcaseView>