Set custom style to textviews inside a custom view in android
Set custom style to textviews inside a custom view in android
I have a custom view class DoubleTextView.java which looks like below,
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;
}
}
Attributes to be set in DoubleTextView.class is below,
<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>
I am unable to add custom styles to the two textviews present in my DoubleTextView.java class. Custom styles are present in my styles.xml
This is how I am trying to use this,
<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"/>
But it is throwing error when app:styleUpText is used in xml ,
Method threw 'java.lang.UnsupportedOperationException' exception.
Thanks in advance
1 Answer
1
Use getResourceId
instead of getInteger
for a style attribute.
getResourceId
getInteger
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thanks a lot. Worked like a charm
– Prashast
Jun 29 at 10:37