gpt4 book ai didi

android - 如何从 TypedArray 获取标志属性?

转载 作者:太空宇宙 更新时间:2023-11-03 13:51:56 24 4
gpt4 key购买 nike

我在 android 自定义 TextView 中设置了多个标志属性,如何使用 TypedArray 恢复这些属性

<some.text.view.that.i.defined.TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
font:sanFrancisco="bold|italic"/>


<attr name="fontSanFrancisco">
<flag name="regular" value="0"/>
<flag name="bold" value="1"/>
<flag name="italic" value="2"/>
</attr>

<declare-styleable name="font">
<attr name="sanFrancisco" format="flag"/>
</declare-styleable>

最佳答案

attrs.xml

  <resources>
<declare-styleable name="font">
<attr name="my_sampleFlag" />
</declare-styleable>
<attr name="my_sampleFlag">
<flag name="regular" value="0" />
<flag name="bold" value="1" />
<flag name="italic" value="2" />
</attr>
</resources>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<com.example.checkstack.MyView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Hello World"
android:layout_marginTop="20dip"/>
</LinearLayout>

我的 View

public class MyView extends TextView {

public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
applyCustomFont(context, attrs);
}

public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
applyCustomFont(context, attrs);
}

private void applyCustomFont(Context context, AttributeSet attrs) {

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.font);
int textStyle = a.getInt(R.styleable.font_my_sampleFlag, 1);
setTypeface(null, textStyle);
a.recycle();
}
}

关于android - 如何从 TypedArray 获取标志属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34279970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com