在 android 的自定义视图中将自定义样式设置为文本视图

Set custom style to textviews inside a custom view in android

我有一个自定义视图 class DoubleTextView.java 如下所示,

public class DoubleTextView extends LinearLayout {
    LinearLayout layout;
    TextView upTextView;
    TextView downTextView;
    Context mContext;

    public DoubleTextView(Context context) {

        super(context);
        mContext = context;
    }

    public DoubleTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;


        String service = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater li = (LayoutInflater) getContext().getSystemService(service);

        layout = (LinearLayout) li.inflate(R.layout.custom_double_text, this, true);

        upTextView = layout.findViewById(R.id.text_up);
        downTextView = layout.findViewById(R.id.text_down);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DoubleTextView);

        String upText = a.getString(R.styleable.DoubleTextView_upText);
        String downText = a.getString(R.styleable.DoubleTextView_downText);
        int upTextStyle = a.getInteger(R.styleable.DoubleTextView_styleUpText,R.style.ListOtherLightInfo);
        int downTextStyle = a.getInteger(R.styleable.DoubleTextView_styleDownText,R.style.ListOtherLightInfo);

        upText = upText == null ? "" : upText;
        downText = downText == null ? "" : downText;

        upTextView.setText(upText);
        downTextView.setText(downText);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            upTextView.setTextAppearance(R.style.ListOtherLightInfo);
            downTextView.setTextAppearance(downTextStyle);
        }
        a.recycle();
    }

    public DoubleTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
    }
}

要在DoubleTextView.class中设置的属性如下,

<declare-styleable name="DoubleTextView">
        <attr name="upText" format="string"/>
        <attr name="downText" format="string"/>
        <attr name="styleUpText" format="reference"/>
        <attr name="styleDownText" format="integer"/>

    </declare-styleable>

我无法向 DoubleTextView.java class 中的两个文本视图添加自定义样式。自定义样式存在于我的 styles.xml

这就是我尝试使用它的方式,

<com.loconav.common.widget.DoubleTextView
                                app:upText="heklow"
                                app:downText="askjdnakjsndjasndjkasndasndj"
                                app:styleUpText="@style/BoldTextBlue"
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"/>

但是在 xml ,

中使用 app:styleUpText 时会抛出错误

方法抛出 'java.lang.UnsupportedOperationException' 异常。

提前致谢

使用 getResourceId 而不是 getInteger 作为样式属性。