为包含多个内部文本视图的自定义Android视图创建“主题”

3

我有一个名为“address_view.xml”的自定义视图,它显示一个人的姓名和街道地址,定义如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:orientation="vertical">

    <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:text="John Smith"/>

    <TextView
            android:id="@+id/street_address"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:maxLines="2"
            tools:text="1 Main St."/>
</LinearLayout>

这个视图在我的应用的多个页面中使用,但每个TextView都有2种字体、文本颜色和大小的变化。

是否可以为此视图创建“主题”,分别设置名称和地址TextView的textFont/textColor?例如,我想做这样的事情:

<com.example.view.AddressView
    ...
    style="@style/Theme1" />

这段代码将“name” TextView 设置为使用 FontA、ColorA 和 Size1,并将“address” TextView 设置为使用 FontB、ColorB 和 Size2。

这样,我可以在某些页面上使用 Theme1,并创建另一个“Theme2”,使用第二种字体/颜色/大小组合,并在其他页面上使用它。

1个回答

1
你需要首先定义自定义属性,然后在样式中使用它们。我将以三角形的样式为例进行说明。
首先,在/res/attrs.xml中定义您想要更改的属性。
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Triangle">
        <attr name="triangleColor" format="color"/>
        <attr name="triangleStrokeColor" format="color"/>
        <attr name="triangleStrokeWidth" format="dimension"/>
    </declare-styleable>
</resources>

在您的自定义视图中,您需要读取您传递的值。
 // Get the values from XML
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.Triangle, style, 0);

int tmp;

mTriangleColor = typedArray.getColor(R.styleable.Triangle_triangleColor, mTriangleColor);
mStrokeColor = typedArray.getColor(R.styleable.Triangle_triangleStrokeColor, mStrokeColor);

tmp = typedArray.getDimensionPixelSize(R.styleable.Triangle_triangleStrokeWidth, -1);
mStrokeWidth = tmp != -1 ? tmp : 2 * density; // Use 2dp as a default value

// Don't forget this!
typedArray.recycle();

然后定义样式。注意: 自定义属性项不需要xml命名空间,因此没有android:
<style name="defaultTriangle">
    <item name="triangleColor">#FF33B5E5</item>
    <item name="triangleStrokeColor">@android:color/black</item>
    <item name="triangleStrokeWidth">3dp</item>
</style>

然后只需要应用。
<some.package.Triangle
    style="@style/defaultTriangle"
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:layout_weight="1"
    android:padding="10dp"
    android:rotation="0"
    />

这对文本字体如何工作?我的字体作为单独的.ttf文件包含在assets/文件夹中。 - Yiling
你可以创建一个字符串类型的属性,然后将字体文件的路径作为字符串提供。在视图中,你可以读取该路径并使用它。 - Bojan Kseneman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接