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

后端 未结 4 1144
借酒劲吻你
借酒劲吻你 2020-12-08 22:03

The below code gives Resources$NotFoundException

TypedValue value = new TypedValue();
((Activity)context).getResources().getValue(android.R.attr         


        
相关标签:
4条回答
  • 2020-12-08 22:14

    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());
    
    0 讨论(0)
  • 2020-12-08 22:19

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

    0 讨论(0)
  • 2020-12-08 22:23

    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.

    0 讨论(0)
  • 2020-12-08 22:24

    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.

    0 讨论(0)
提交回复
热议问题