Skip to content Skip to sidebar Skip to footer

Android: How To Get Value Of "listpreferreditemheight" Attribute In Code?

The below code gives Resources$NotFoundException TypedValue value = new TypedValue(); ((Activity)context).getResources().getValue(android.R.attr.listPreferredItemHeight, value, tru

Solution 1:

This works:

TypedValuevalue=newTypedValue();
((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.TypedValuevalue=newandroid.util.TypedValue();
booleanb= getTheme().resolveAttribute(android.R.attr.listPreferredItemHeight, value, true);
Strings= TypedValue.coerceToString(value.type, value.data);
android.util.DisplayMetricsmetrics=newandroid.util.DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
floatret= value.getDimension(metrics);

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

Solution 2:

Another answer

publicfloatgetItemHeight() {
    TypedValuevalue=newTypedValue();
    DisplayMetricsmetrics=newDisplayMetrics();

    context.getTheme().resolveAttribute(
            android.R.attr.listPreferredItemHeight, value, true);
    ((WindowManager) (context.getSystemService(Context.WINDOW_SERVICE)))
            .getDefaultDisplay().getMetrics(metrics);

    return TypedValue.complexToDimension(value.data, metrics);
}

it maybe more useful.

Solution 3:

Femi's answer was very helpful. Without wanting to detract from his answer, I've taken the logic and placed it in a library convenience method that you should be able to plug-and-play. I plan on updating the code with other attribute methods over time. I hope it proves useful to someone.

(Note that I discovered Resources.getDisplayMetrics() seems to be an easier way to return display metrics rather than querying the WindowManager.)

Solution 4:

The shortest answer (without DisplayMetrics):

TypedValuetypedValue=newTypedValue();
context.getTheme().resolveAttribute(android.R.attr.listPreferredItemHeight, typedValue, true);
intheight= TypedValue.complexToDimensionPixelSize(typedValue.data, context.getResources().getDisplayMetrics());

Post a Comment for "Android: How To Get Value Of "listpreferreditemheight" Attribute In Code?"