【问题标题】:Imagebutton in TableLayout too bigTableLayout 中的 Imagebutton 太大
【发布时间】:2017-11-22 03:14:07
【问题描述】:

我有一个 Scrollview,里面有一个 Tablelayout。 Tablelayout 在 xml 中定义如下:

<TableLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/tablelayout"/>

tablelayout 的行及其视图以编程方式添加,如下所示:

private void createFeedLayout(int menuId, int newestOrBest, int count, int startId) {

TableLayout tbl = (TableLayout)FindViewById(Resource.Id.tablelayout);
List<Helpers.Objects.Picture> pictures = getPictures(menuId, newestOrBest, startId, count);
TableRow row = new TableRow(this);

tbl.AddView(row);
row.SetBackgroundResource(Resource.Drawable.background_whitebar_challengeopen);

foreach (Helpers.Objects.Picture picture in pictures)
{
    if (counter == PICTURESINAROW) 
    {
        row = new TableRow(this);
        row.SetGravity(GravityFlags.Left);
        row.SetBackgroundResource(Resource.Drawable.background_whitebar_challengeopen);
        tbl.AddView(row);
        counter = 0;
    }

    Bitmap bmp_picture = PhotoHelpers.DecodePhotoFromBase64(picture.photo);
    bmp_picture = PhotoHelpers.ResizeImage(bmp_picture, (Resources.DisplayMetrics.WidthPixels / PICTURESINAROW) - SPACEBETWEENPICS, 
                                                       (Resources.DisplayMetrics.WidthPixels / PICTURESINAROW) - SPACEBETWEENPICS, false); 

    ImageButton button = new ImageButton(this);
    button.Id = i;
    button.Click += openImage;
    button.SetImageBitmap(bmp_picture);
    button.SetBackgroundColor(Color.Red);
    button.SetAdjustViewBounds(true);

    row.AddView(button);
    counter++;
    i++;
    }
}   

}

代码在 Tablerow 中添加 3 张图片,然后创建一个新行。预期的结果是 3 张图片彼此直接相邻,从屏幕的左边缘开始。

但我得到的是这样的:

(只有红色背景部分重要)

在这里我很困惑。我为每个按钮添加了SetAdjustViewBounds(true);,并认为这会使按钮与图片一样大。因此SetBackgroundColor(Color.Red); 根本不重要。但似乎按钮周围有一个大框架。

有人知道什么会导致这种行为吗?

提前致谢!

【问题讨论】:

  • 使用button.Background方法代替button.SetImageBitmap(bmp_picture)方法: button.Background = new BitmapDrawable(Resources, bmp_picture);
  • 嗨。我试过这个,但现在图片只会被拉伸。所以它不再是方形的了。对我来说,Tablelayout 似乎对 tablerow 中的每一列都有一个静态宽度,因此按钮被拉伸以满足要求。这可能吗?
  • tablerow中每一列的宽度由自己决定,位图的宽度。

标签: c# android xamarin layout imageview


【解决方案1】:

如果你想让你的图片按钮包裹内容,你需要设置 LayoutParameters。试试这个:

button.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);

【讨论】:

  • 您好,感谢您的回答。我已经尝试过了,但它并没有改变任何东西。令人困惑的是。如果我通过button.LayoutParameters.Width 获得按钮的宽度,则大小似乎是正确的。但是它周围仍然有红色边框......
【解决方案2】:

好的,我让它工作了。问题是 TableLayout 本身。屏幕中间的圆形图片也是该布局的一部分。 “红色”区域中的 TableRows 以某种方式适应了这些先前 TableRows 的列宽。

因此,我创建了一个新的 TableLayout 并将底部图片的 TableRows 添加到它。

我确信有更好的解决方案,但至少现在可以使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多