Change custom button size for layouts and containers

可紊 提交于 2019-12-05 16:56:08

To understand what happens here you need to look in the Android source. There is a method in ViewGroup generateLayoutParams which JavaDoc states:

Returns a safe set of layout parameters based on the supplied layout params. When a ViewGroup is passed a View whose layout params do not pass the test of checkLayoutParams(android.view.ViewGroup.LayoutParams), this method is invoked. This method should return a new set of layout params suitable for this ViewGroup, possibly by copying the appropriate attributes from the specified set of layout params.

If you look at LinearLayout and AbsListView (the parent of GridView) source you'll see they convert their children layout params to LinearsLayout.LayoutParams and AbsListView.LayoutParams respectively. But this conversion only happens when the child is added to the layout.
Thus if you add your TouchButton to the LinearLayout (programmaticaly or via XML) it will receive LinearsLayout.LayoutParams and, if you add it to the GridView (via an adapter) it receives AbsListView.LayoutParams.
But if you set layout params manually afterwards, you will get ClassCastException somewhere in the parent container code (since it expects its children layout params to be of some specific type).

For the solution of your issue I suggest you the following:

private void setLayout(buttonsize_t size) {

    log("Setting Layout: "+buttonsize_t.getPxl(size));

    final float scale = getContext().getResources().getDisplayMetrics().density;
    int dim = (int) (buttonsize_t.getPxl(size) * scale + 0.5f);

    ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) getLayoutParams();
    if (params != null) {  
        params.height = dim;
        params.width = dim;
        setLayoutParams(params);
    } else {
      // the LayoutParams was not set yet, it must be the GridView 
      // which delays setting till child rendering
      params = new AbsListView.LayoutParams(dim, dim);
      setLayoutParams(params);
    }
}

Why are you casting LayoutParams at all?

Button.getLayoutParams() should return ViewGroup.LayoutParams, which you can access the height and width on - no cast needed. Are you sure when you tried ViewGroup.LayoutParams you didn't do something like:

ViewGroup.LayoutParams params = (AbsListView.LayoutParams) getLayoutParams();

(That'll still fail).

In any case, use this:

ViewGroup.LayoutParams params = getLayoutParams();

Then if you still get an exception, post that one - not the one with the casting.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!