[关闭]
@act262 2017-09-19T05:17:39.000000Z 字数 2393 阅读 2146

Android Studio自定义View布局预览问题

AndroidStudio


需求是想自定义一个全局通用样式的确认按钮,又不想在每个View后面都去引用这个样式,所以将默认属性放在了全局的主题属性中,然后在自定义View中引用这个样式。只要使用这个自定义View,然后设置一些基本属性就可以使用了,对默认属性不能满足的情况还可以在布局中修改特定属性就可以了。

  1. // 比如某个地方要用到这个按钮,就引用这个公用样式ConfirmButtonStyle,然后就是重复这么搞了
  2. <io.micro.widget.ConfirmButton
  3. style="@style/ConfirmButtonStyle"
  4. android:layout_width="wrap_content"
  5. android:layout_height="wrap_content"
  6. android:enabled="false"
  7. android:text="@string/sure"
  8. android:textColor="@color/pub_btn_color_1" />

不想重复copy这个style

  1. <!-- 自定义组件主题属性 -->
  2. <attr name="Attr.Widget.ConfirmButton" format="reference" />
  3. <!-- Base application theme. -->
  4. <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
  5. <item name="colorPrimary">@color/c_ff0a1437</item>
  6. <item name="colorPrimaryDark">@color/c_ff0a1437</item>
  7. // 一些全局属性的配置
  8. <item name="Attr.Widget.ConfirmButton">@style/ConfirmButtonStyle</item>
  9. </style>
  10. <!-- 确认类按钮的默认样式 -->
  11. <style name="ConfirmButtonStyle" parent="Widget.AppCompat.Button">
  12. <item name="android:text">@string/confirm</item>
  13. <item name="android:textSize">@dimen/text_px_50</item>
  14. <item name="android:textColor">@android:color/white</item>
  15. <item name="android:minHeight">@dimen/ui_px_120</item>
  16. <item name="android:minWidth">@dimen/ui_px_560</item>
  17. <item name="android:gravity">center</item>
  18. <item name="android:background">@drawable/selector_confirm_button</item>
  19. </style>
  1. public class ConfirmButton extends android.support.v7.widget.AppCompatButton {
  2. public ConfirmButton(Context context) {
  3. this(context, null);
  4. }
  5. public ConfirmButton(Context context, AttributeSet attrs) {
  6. this(context, attrs, R.attr.Attr_Widget_ConfirmButton);
  7. }
  8. public ConfirmButton(Context context, AttributeSet attrs, int defStyleAttr) {
  9. super(context, attrs, defStyleAttr);
  10. init();
  11. }
  12. private void init() {
  13. // xxx
  14. }
  15. }

在布局中使用自定义按钮

  1. <io.micro.widget.ConfirmButton
  2. android:layout_width="wrap_content"
  3. android:layout_height="wrap_content"
  4. android:enabled="false"
  5. android:text="@string/sure"
  6. android:textColor="@color/pub_btn_color_1" />

AS预览不正常,但是部署到手机是正常的

AS的提示:

  1. Failed to find style 'Attr_Widget_ConfirmButton' in current theme
  2. Missing styles. Is the correct theme chosen for this layout? Use the Theme combo box above the layout to choose a different layout, or fix the theme style references.

解决方案:AS 预览主题配置为当前的主题,比如使用当前对应的主题AppTheme
But在已配置当前主题的情况下AS预览还是没有我们想要的效果。

最后发现是属性命名问题,不能带有下划线的属性名,虽然编译没问题,但是在预览下不正常。估计是AS的一个小问题吧。

Attr.Widget.ConfirmButton -> R.attr.Attr_Widget_ConfirmButton
属性名之间的.R.java变成_
.改成下划线或者去掉就可正常预览了。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注