【问题标题】:Android custom view: can't add own stylesAndroid自定义视图:无法添加自己的样式
【发布时间】:2015-02-16 07:44:44
【问题描述】:

我发现了一项改进,它可能有助于不将视图值硬编码到我的 android 应用程序中的 java 类中。我想知道我怎样才能让它工作。我想在我的适配器中使用这种视图(这意味着我不能在布局的根目录中使用 @style 属性)。我做错了什么?

代码:

styles.xml:

<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="customViewStyleRef">@style/CustomViewStyle</item>
    </style>

    <attr name="customViewStyleRef" format="reference"/>

    <style name="CustomViewStyle" parent="@android:style/Widget.TextView">
        <item name="android:layout_margin">10dp</item>
    </style>
</resources>

查看类:

public class CustomView extends View {
    public CustomView(Context context) {
        super(context, null);
    }

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs, R.attr.customViewStyleRef);
    }

    public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, R.attr.customViewStyleRef);
    }

    public void init(@NonNull ViewGroup parentView) {
        inflate(getContext(), R.layout.custom_view, parentView);
    }
}

视图布局:

<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#f00"
            android:textColor="#fff"
            android:textSize="50sp"
            android:text="test text"/>
</merge>

问题:TextView 容器没有我在 styles.xml 中指定的任何填充(见图)。

【问题讨论】:

    标签: android android-view android-styles


    【解决方案1】:

    您应该初始化 TextView,然后使用 TextView 的样式,或者您可以通过将样式名称放在 TextView 中并为 TextView 使用 id 来解决此问题,这将有助于使用它。

    <TextView
            android:id="@+id/custom_tv"
            style="@style/CustomViewStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#f00"
            android:textColor="#fff"
            android:textSize="50sp"
            android:text="test text"/>
    

    【讨论】:

    • 但我想使用 元素
    • ContextThemWrapper 可能对你有帮助 TextView myText = new TextView(new ContextThemeWrapper(MyActivity.this, R.style.CustomViewStyle));
    • 上下文包装方法有效,但为嵌套子项设置包装样式。这在几种情况下可能会有所帮助,但在我的场合我想避免这种情况。不过谢谢
    【解决方案2】:

    我想我已经想通了。我构建的文件以某种方式被缓存,我无法让它工作。而且我采用了错误的测试参数。我的方法奏效了?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多