Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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);
like image 887
ab11 Avatar asked May 12 '11 17:05

ab11


4 Answers

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.

like image 196
Femi Avatar answered Oct 15 '22 17:10

Femi


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.

like image 24
kewang Avatar answered Oct 15 '22 17:10

kewang


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.)

like image 8
Garret Wilson Avatar answered Oct 15 '22 18:10

Garret Wilson


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());
like image 2
user1185087 Avatar answered Oct 15 '22 18:10

user1185087