簡體   English   中英

以編程方式將子級添加到GridLayout

[英]Programmatically add child to GridLayout

我做了一個自定義的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>

我正在嘗試創建一個使用“自定義”單元格制作的游戲板,但是我無法確定簡單/正確的執行方法,也無法將視圖添加到特定的行和列,這可能會很有幫助。

嘗試這個,

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

暫無
暫無

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

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