Android: How to Get Value of an Attribute in Code

Android: how to get value of an attribute in code?

Your code only gets the resource ID of the style that the textAppearanceLarge attribute points to, namely TextAppearance.Large as Reno points out.

To get the textSize attribute value from the style, just add this code:

int[] textSizeAttr = new int[] { android.R.attr.textSize };
int indexOfAttrTextSize = 0;
TypedArray a = context.obtainStyledAttributes(typedValue.data, textSizeAttr);
int textSize = a.getDimensionPixelSize(indexOfAttrTextSize, -1);
a.recycle();

Now textSize will be the text size in pixels of the style that textApperanceLarge points to, or -1 if it wasn't set. This is assuming typedValue.type was of type TYPE_REFERENCE to begin with, so you should check that first.

The number 16973890 comes from the fact that it is the resource ID of TextAppearance.Large

How to get an ?attr/ value programmatically

As commented from @pskink:

    TypedValue value = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.editTextColor, value, true);
getView().setBackgroundColor(value.data);

will pull the attribute from the theme currently assigned to the context.

Thanks @pskink!

Android studio get attribute value

I just found a super easy way to find out the value.

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="?android:textColorPrimary" />

And you want to know what the actual color will be.

You can simply place your cursor at the ?android:textColorPrimary part and click View -> Quick Documentation (or hit F1 or whatever the hotkey you have assigned to that action):

Sample Image

You can go to Design tab and switch parameters like API level, then go back to Text tab, and hitting F1 will show you the value for those new parameters.


Below is a more winded way to get the same:

For some attributes that are key to your theme, like android:textColorPrimary, it is possible to view and edit them through Tools > Android > Theme Editor.

appcompat.light

Other than that, if you are interested in the value of the attribute used by some particular view in your layout, you can use the layout editor to select that view, then in the Properties pane select View all properties, find the one you are interested in and it should show you the default attribute used for this property, for example:

property

You could then click on the color to get a window to search resources, that also shows you how Android resolves attributes to concrete values:

resources

How to obtain the value for a reference attribute

You can't receive reference via findViewById in constructor. Because it is not attached to layout yet.
Reference: https://developer.android.com/training/custom-views/create-view.html#applyattr

When a view is created from an XML layout, all of the attributes in
the XML tag are read from the resource bundle and passed into the
view's constructor as an AttributeSet. Although it's possible to read
values from the AttributeSet directly, doing so has some
disadvantages:

Resource references within attribute values are not resolved Styles
are not applied Instead, pass the AttributeSet to
obtainStyledAttributes(). This method passes back a TypedArray array
of values that have already been dereferenced and styled.

You can receive in another methods.
For example:

attrs.xml

 <declare-styleable name="CustomTextView">
<attr name="viewPart" format="reference"></attr>
</declare-styleable>

yourLayout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:gravity="center_vertical"
android:orientation="horizontal">

<tr.com.ui.utils.CustomTextView
android:id="@+id/chat_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|bottom"
android:focusableInTouchMode="false"
android:gravity="left"
android:text="test"
app:viewPart="@id/date_view" />

<TextView
android:id="@+id/date_view"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:gravity="right" />

</LinearLayout>

CustomTextView.java

   public class CustomTextView extends TextView {
private View viewPart;
private int viewPartRef;

public CustomTextView(Context context) {
super(context);
}

public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView, 0, 0);

try {
viewPartRef = a.getResourceId(R.styleable.CustomTextView_viewPart, -1);
} catch (Exception e) {
e.printStackTrace();
}

}

@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
viewPart = ((View) this.getParent()).findViewById(viewPartRef);
}

public View getViewPart() {
return viewPart;
}

public void setViewPart(View viewPart) {
this.viewPart = viewPart;
}}

You can decide your scenario and modify this code.

Android: how to get value of listPreferredItemHeight attribute in code?

This works:

TypedValue value = new TypedValue();
((Activity)context).getTheme().resolveAttribute(android.R.attr.listPreferredItemHeight, value, true);

EDIT: You get zero because haven't initialized the DisplayMetrics instance properly. It needs a frame of reference (a display) to do any meaningful conversion.

android.util.TypedValue value = new android.util.TypedValue();
boolean b = getTheme().resolveAttribute(android.R.attr.listPreferredItemHeight, value, true);
String s = TypedValue.coerceToString(value.type, value.data);
android.util.DisplayMetrics metrics = new android.util.DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
float ret = value.getDimension(metrics);

On my Nexus 1 s is 64.0dip and ret is 96.

How to get the value of a custom attribute (attrs.xml)?

No, this is not the correct way, as the integer R.attr.customColorFontContent is a resource identifier generated by Android Studio when your app is compiled.

Instead, you'll need to get the color that is associated with the attribute from the theme. Use the following class to do this:

public class ThemeUtils {
private static final int[] TEMP_ARRAY = new int[1];

public static int getThemeAttrColor(Context context, int attr) {
TEMP_ARRAY[0] = attr;
TypedArray a = context.obtainStyledAttributes(null, TEMP_ARRAY);
try {
return a.getColor(0, 0);
} finally {
a.recycle();
}
}
}

You can then use it like this:

ThemeUtils.getThemeAttrColor(context, R.attr.customColorFontContent);

How to get a value of color attribute programmatically

I believe instead of this:



TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
int color = typedValue.data;

You should do this:



TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
int color = ContextCompat.getColor(this, typedValue.resourceId)



Related Topics



Leave a reply



Submit