簡體   English   中英

如何在android中以編程方式為視圖(不是viewGroup)設置layout_margin

[英]how to set layout_margin for a view (not for a viewGroup) programmatically in android

在為GridLayout動態創建的ImageView以編程方式設置layout_margin時,我遇到了問題。 我試過以下代碼:


GridLayout gridLayout = (GridLayout) findViewById(R.id.idGridLayout);

    gridLayout.setColumnCount(10);
    gridLayout.setRowCount(10);


    for (int i = 1; i <= 100; i++) {
        ImageView tile1 = new ImageView();
        LayoutParams lp = new LayoutParams(100, 100);

        tile1.setLayoutParams(lp);
       lp.setMargins(4, 4, 4, 4); ////not working some error
        tile1.setBackgroundColor(Color.rgb(255, 255, 5));
        //tile1.setBackgroundResource(R.drawable.aalien);
        //tile1.setBackgroundColor();

我找到了一個方法setMargins(4, 4, 4, 4) ,但是通過這種方式,我只能為諸如LinearLayout / GridLayout / RelativeLayout等的ViewGroups設置邊距。

但是我想像使用android:layout_margin="5dp"xml那樣為ImageView設置邊距

嘗試對每個ImageView執行此操作

ImageView imageView = new ImageView(context);

GridLayout.LayoutParams params = (GridLayout.LayoutParams) imageView.getLayoutParams();

params.setMargins(4, 4, 4, 4); // left, top, right, bottom

imageView.setLayoutParams(params);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM