簡體   English   中英

設置高度等於寬度,寬度歸因於重量

[英]Setting height equal to width with width being attributted by weight

我正在為Android開發基於2048的游戲,我添加的功能之一是可以使用4x4到8x8的網格,但是在分配磁貼大小時遇到​​了問題。 我有一個LinearLayout,其中包含其他LinearLayouts,每行一個(網格高度),每行內的TextViews用於該行中的每個圖塊。 每個textview的權重為1,包含它們的行的weightSum等於width(以圖塊為單位),width設置為match_parent,然后在將textviews添加到布局中以使其具有正方形后,將高度設置為等於寬度。 我通過代碼執行此操作,為每個圖塊填充預定義的textview並將其添加到行中,然后將該行添加到“ board”視圖中。 但這不起作用。

這是一段相關的代碼,它在onCreate方法中為視圖分配了寬度,高度和權重:

        board = (LinearLayout) findViewById(R.id.board);
        board.setWeightSum(1.0f * height);

        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        for (int i = 0; i < height; i++) {

            LinearLayout row = (LinearLayout) inflater.inflate(R.layout.row_ll, null);
            lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
            row.setId(1000 + i);
            row.setWeightSum(1.0f * width);

            for (int j = 0; j < width; j++) {

                tv = (TextView) inflater.inflate(R.layout.text_view, null);

                tv.setId(nextId());

                row.addView(tv, lp);

            }

            board.addView(row);

            for (int j = 0; j < width; j++) {

                tv = (TextView) findViewById((i * width) + j + 1);
                tv.setHeight(tv.getMeasuredWidth());
                System.out.println("h:" + tv.getHeight() + "; w:" + tv.getWidth());

            }

        }

text_view:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text_view"
android:layout_width="0dip"
android:layout_height="0dip"
android:background="@drawable/bg_tv"
android:gravity="center"
android:text="@string/zero"
android:textColor="@color/text"
android:textSize="16sp"
android:layout_weight="1" >

</TextView>

row_ll

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/row_ll"
android:layout_width="match_parent"
android:layout_height="64dip"
android:background="@drawable/bg_tv"
android:orientation="horizontal"
android:weightSum="4">

</LinearLayout>

其余代碼可在https://github.com/lhamaware/2048中找到

您需要在測量階段設置高度。 為此,創建一個擴展TextView的自定義視圖,並覆蓋onMeasure

public void onMeasure(int widthSpec, int heightSpec) {
  super.onMeasure(widthSpec, heightSpec);
  int width = getMeasuredWidth();
  setMeasuredDimension(width, width);
}

請參閱我的博客文章以了解更多信息: http : //blog.sqisland.com/2012/01/android-square-view.html

暫無
暫無

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

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