设置高度等于宽度,宽度由重量决定

时间:2014-03-30 18:39:19

标签: java android android-layout

我正在为Android制作一款基于2048的游戏,我已添加的功能之一是可能有4x4到8x8的网格,但我在分发时遇到问题瓷砖的大小。我有一个包含其他LinearLayout的LinearLayout,每行一个(网格高度),并且在该行的每个tile中每行TextViews。每个textview的权重为1,包含它们的行的weightSum等于width(在tile中),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

找到

1 个答案:

答案 0 :(得分:5)

您需要在测量阶段设置高度。为此,请制作一个展开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