2016-11-17 3 views
1

Я делаю игру tic-tac-toe, и мне нужно сделать ширину и высоту моих кнопок одинаковыми.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, ПИД: 20927 java.lang.ClassCastException: android.view.ViewGroup $ LayoutParams не может быть приведены к android.widget.LinearLayout $ LayoutParams

ответ

1

Вместо 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 (размер); int buttonwidth = (int) (size.x/3);

Тогда вы просто передать эту переменную вместо SIZE так:

button.setLayoutParams(new LinearLayout.LayoutParams(buttonwidth, buttonwidth)); 
+0

это не работает. Хотя теперь мое приложение не падает, ширина и высота кнопок не совпадают. – lmiguelvargasf

+0

Я обновил свой ответ. –

+0

это работает. Однако в конце концов я хотел прочитать ширину экрана и взять третью часть в качестве ширины моей кнопки, но спасибо. Ваш ответ решает мой вопрос. – lmiguelvargasf