具有相同宽度和高度的Android按钮?
问题描述:
我想提出一个井字棋游戏,我需要让我的按钮相同的宽度和高度。具有相同宽度和高度的Android按钮?
这是我的xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center_horizontal" ...>
<TextView
android:textSize="30dp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tic-Tac-Toe" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/cell_00"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/cell_10"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/cell_20"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<!--previous linear layout repeats twice more-->
</LinearLayout>
这是我的活动:
// imports
import android.view.ViewGroup;
public class TicTacToeActivity extends AppCompatActivity {
private static final int SIZE = 3;
@BindView(R.id.game_feedback)
TextView gameFeedback;
private Button[][] grid = new Button[SIZE][SIZE];
private int[][] cell_ids = {
{R.id.cell_00, R.id.cell_01, R.id.cell_02},
{R.id.cell_10, R.id.cell_11, R.id.cell_12},
{R.id.cell_20, R.id.cell_21, R.id.cell_22}
};
private Button getButtonById(int id) {
return (Button) findViewById(id);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tic_tac_toe);
ButterKnife.bind(this);
gameFeedback.setVisibility(View.INVISIBLE);
loadGridButtons();
Button button = (Button) findViewById(R.id.cell_00);
int size = button.getLayoutParams().width;
button.setLayoutParams(new ViewGroup.LayoutParams(size, size));
}
private void loadGridButtons() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
grid[i][i] = getButtonById(cell_ids[i][j]);
}
}
}
}
不过,我收到以下错误崩溃我的应用程序。
致命异常:主 工艺:com.mathsistor.m.tictactoe,PID:20927 java.lang.ClassCastException:android.view.ViewGroup $的LayoutParams 不能转换到android.widget.LinearLayout $的LayoutParams
答
代替button.setLayoutParams(new ViewGroup.LayoutParams(size, size));
使用button.setLayoutParams(new LinearLayout.LayoutParams(size, size));
UPDATE 变化(size, size)
到(SIZE, SIZE)
如果这是你正在使用的变量。否则,将该变量替换为您想要的任何大小。
UPDATE 2
为了得到屏幕的宽度和除以3,可以做到这一点: 显示显示= getWindowManager()getDefaultDisplay(); 点大小=新点(); display.getSize(size); INT buttonwidth =(int)的(size.x/3);
然后你简单地传递变量而非SIZE
像这样:
button.setLayoutParams(new LinearLayout.LayoutParams(buttonwidth, buttonwidth));
这是行不通的。虽然现在我的应用程序不会崩溃,但按钮的宽度和高度并不相同。 – lmiguelvargasf
我更新了我的答案。 –
这是工作。但是,最终我想要的是读取屏幕宽度,并将第三部分作为我的按钮宽度,但是谢谢。你的回答解决了我的问题。 – lmiguelvargasf