且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

更改自定义按钮尺寸布局和容器

更新时间:2023-11-26 23:32:58

要了解这里发生了什么,你需要在Android源看。有一个在ViewGroup中的方法 generateLayoutParams 的Javadoc的状态:

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

,则返回一个安全组的基础上所提供的布局的布局参数
  PARAMS。当一个ViewGroup中传递一个查​​看其布局PARAMS不
  通过考验
   checkLayoutParams(android.view.ViewGroup.LayoutParams) ,这种方法是
  调用。这个方法应该返回一组新的布局适合PARAMS
  这个ViewGroup中,可能是通过复制适当的属性
  从指定的一组布局则params的。

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.

如果你看的LinearLayout和AbsListView(GridView控件的母公司)的源你会看到它们转换成自己的孩子布置PARAMS到 LinearsLayout.LayoutParams AbsListView.LayoutParams 分别。但是,当儿童被添加到布局此转换才会发生。结果,
因此,如果您添加TouchButton到的LinearLayout(programmaticaly或通过XML),将获得 LinearsLayout.LayoutParams ,如果你(通过转接器)将其添加到GridView接收 AbsListView.LayoutParams 。结果
但是,如果你设置布局PARAMS手动之后,您将获得 ClassCastException异常某处父容器code(因为它预计其子女布局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);
    }
}