The below code gives Resources$NotFoundException
TypedValue value = new TypedValue();
((Activity)context).getResources().getValue(android.R.attr.listPreferredItemHeight, value, true);
EDIT: More code added in response to answer.
When I run the below code, all members of displayMetrics
are 0. As is ret
.
TypedValue value = new TypedValue();
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity)context).getTheme().resolveAttribute(android.R.attr.listPreferredItemHeight, value, true);
float ret = value.getDimension(displayMetrics);
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.
Another answer
public float getItemHeight() {
TypedValue value = new TypedValue();
DisplayMetrics metrics = new DisplayMetrics();
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.
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.)
The shortest answer (without :DisplayMetrics
)
TypedValue typedValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.listPreferredItemHeight, typedValue, true);
int height = TypedValue.complexToDimensionPixelSize(typedValue.data, context.getResources().getDisplayMetrics());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With