【问题标题】:Programmatically set ImageButton margins以编程方式设置 ImageButton 边距
【发布时间】:2016-11-23 07:16:53
【问题描述】:

我已经创建了很多这样的代码图像按钮:

TableRow tr = new TableRow(this);
if (db != null) {
        if (db.moveToFirst()) {
            do {
                ImageButton button = new ImageButton(this);
                int ID = Integer.parseInt(db.getString(db.getColumnIndex("ID")));
                int resource = getResources().getIdentifier("unit" + ID, "drawable", getPackageName());
                System.out.println("unit" + ID + ":" + resource);
                button.setImageResource(resource);
                button.setOnClickListener(MainActivity.this);
                tr.addView(button);
                button.getLayoutParams().height = 250;
                button.getLayoutParams().width = 250;
                button.setScaleType(ImageView.ScaleType.FIT_CENTER);
                //button.setLayoutParams(tableRowParams);
                rowcount++;
                if (rowcount % 5 == 0) {
                    layout.addView(tr);
                    tr = new TableRow(this);
                }
            } while (db.moveToNext());
        }
    }

我找到了代码:

        TableLayout.LayoutParams tableRowParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
        tableRowParams.setMargins(0, 0, 0, 0);

并在执行时应用按钮。

button.setLayoutParams(tableRowParams);

会显示错误信息“android.widget.TableLayout$LayoutParams cannot be cast to android.widget.TableRow$LayoutParams”

【问题讨论】:

标签: android


【解决方案1】:

TableLayout.LayoutParams 替换为TableRow.LayoutParams

TableRow.LayoutParams tableRowParams =
        new TableRow.LayoutParams(
            TableRow.LayoutParams.WRAP_CONTENT,
            TableRow.LayoutParams.WRAP_CONTENT);
tableRowParams.setMargins(0, 0, 0, 0);

【讨论】:

  • 谢谢你,这是我的错误
【解决方案2】:

您使用的LayoutParams 的类型取决于视图的容器,而不是视图本身。因此,由于您的按钮位于 TableRow 内,因此您需要使用 TableRow.LayoutParams 而不是现在的 TableLayout.LayoutParams

另外,请注意,如果您需要设置 TableRow 或 Button 的样式,而不是创建类的新实例并以这种方式查看边距,您可以使用 Button button = (Button) LayoutInflater.from(context).inflate(R.layout.button, tr, false); 扩展 XML 布局,然后您可以在 XML 文件中设置边距。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 2015-02-24
    • 2011-01-29
    • 2019-02-08
    • 2019-10-19
    相关资源
    最近更新 更多