【问题标题】:Programmatically add child to GridLayout以编程方式将子级添加到 GridLayout
【发布时间】:2016-01-06 01:43:54
【问题描述】:

我制作了一个自定义 View ,现在我想以编程方式将它添加到 GridLayout 但我不知道该怎么做...

活动:

public class FullScreenGame extends Activity{

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.full_screen_layout);
    GridLayout grid = (GridLayout) findViewById(R.id.cell_grid);
    grid.addView(new CustomCell(this));

  }
}

我正在尝试这样做,但没有显示任何内容。 自定义单元格类:

public class CustomCell extends View{

private Paint shadowPaint , ovalColor;
private int ypad =0, xpad =0, height =150, width = 150;
//TODO calculate spacing properly

public CustomCell(Context context){
    super(context);

}

public CustomCell(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.getTheme().obtainStyledAttributes(attrs,R.styleable.CustomCell,0,0);

    ypad = a.getInteger(R.styleable.CustomCell_ypad,0);
    xpad = a.getInteger(R.styleable.CustomCell_xpad,0);




    init();
}


@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(width+10,height+10);
}

private void init(){
    shadowPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    shadowPaint.setColor(Color.BLACK);
    shadowPaint.setMaskFilter(new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL));

    ovalColor= new Paint(Paint.ANTI_ALIAS_FLAG);
    ovalColor.setColor(Color.WHITE);
    ovalColor.setMaskFilter(new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL));

}


@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.drawOval(xpad    , ypad    , height+5, width+5, shadowPaint);
    canvas.drawOval(xpad+5 , ypad +5, height, width, ovalColor  );



}
}

full_screen_layout.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#1565c0"
    android:rowCount="5"
    android:columnCount="5" 
    android:id="@+id/cell_grid">

    </GridLayout>

我正在尝试创建一个使用自定义单元格制作的游戏板,但我想不出简单/正确的方法来执行它,以及如何将视图添加到特定的行和列,它可以帮助很多.

【问题讨论】:

    标签: android


    【解决方案1】:

    试试这个,

    GridLayout layout = (GridLayout) findViewById(R.id. cell_grid); 
    layout.setUseDefaultMargins(true); 
    layout.setAlignmentMode(ALIGN_BOUNDS); 
    layout.setRowOrderPreserved(false); 
    layout.setLayoutDirection(View.LAYOUT_DIRECTION_RTL); 
    
    layout.addView(childView, new GridLayout.LayoutParams(row, col));
    // 'childView' can be any View object
    

    【讨论】:

    • layout.addView(childView, new GridLayout.LayoutParams(row, col));也不能在构造函数上添加行和列
    猜你喜欢
    • 1970-01-01
    • 2018-01-19
    • 2021-12-02
    • 2012-02-06
    • 2012-11-11
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多