我是Android開發新手,所以我一直在研究一個國際象棋應用程序,以教我自己。但是,我現在卡住了。從本質上講,我需要一個很好的方式提請ImageButtons的8X8格這樣的:如何以編程方式使用ImageButton填充網格?
- 按鈕填滿整個電網
- 格柵間距的按鈕中均勻分佈
- 有按鍵之間沒有縫隙(澄清#2)
- 網格是方形的,它的大小可以控制(我希望能夠根據屏幕大小自動調整大小)。
或者,簡單地說,它應該看起來像一個標準的國際象棋棋盤:)
我試過幾個佈局沒有成功。目前,這是我已經能夠做到最好:
我使用PlayGameActivity內的下列方式(如果董事會應當制定)一個網格佈局:
public void onStart(){
super.onStart();
board = (GridLayout)findViewById(R.id.chessboard);
board.setColumnCount(8);
board.setRowCount(8);
for(int i = 0; i < 8; i++){
for(int j = 0; j < 8; j++){
ImageButton square = squares[i][j] = new ImageButton(this);
GridLayout.LayoutParams params = new GridLayout.LayoutParams();
params.rightMargin = 0;
params.topMargin = 0;
params.height = params.WRAP_CONTENT;
params.width = params.WRAP_CONTENT;
params.setGravity(Gravity.FILL);
params.rowSpec = GridLayout.spec(i);
params.columnSpec = GridLayout.spec(j);
board.addView(square, params);
//board.addView(square);
}
}}
而且棋盤是通過XML定義是這樣的:
<GridLayout
android:id="@+id/chessboard"
android:layout_width="353dp"
android:layout_height="353dp"
android:layout_marginBottom="104dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="104dp"
android:background="#000000"
android:gravity="center_horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintBottom_creator="1"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintTop_creator="1">
</GridLayout>
我發現這種類型的問題已經在Android的XML的形式,所有的解決方案。也許我對這種方法的擔心是基於無知,但我的理解是,我不得不將64個方格複製並粘貼到GridLayout或其他東西中。另外,我不確定如何根據屏幕尺寸調整大小。理想情況下,我正在尋找嚴格的編程解決方案(無論如何,這是我首選的UI設計方法)。
由於我一直試圖讓程序化解決方案發揮作用,所以我只想解決XML解決方案。在這種情況下,董事會中的廣場數量不會改變,因此追求其他解決方案沒有多少理由。但是,在棋盤上,每個相鄰的方格都是相反的顏色。我看到如何用你的方法創建一個圖像按鈕的網格,但是有什麼方法可以在事後不改變顏色(即訪問行中的每一行和每個方塊來改變顏色)? – TheRussianPatzer
我剛剛用我的建議編輯了我的答案。往上看。 – windedmoose
我終於開始實施該解決方案的XML版本,並且它工作的很棒!這不是我原本以爲我想要的解決方案,但實際上結果非常好。如果你按照你的建議將事情分解成碎片,XML是一種很好的做事方式,所以謝謝! – TheRussianPatzer