2

我在for循环中创建 N 个按钮,OnClickListener每个按钮。用户可以单击每个按钮并设置一个数字。之后,我想要TextView在按钮上方和中间显示数字。

我想要的例子

这正是我想要的。灰色背景是按钮,数字是TextView

我现在拥有的代码:

        for (int toShow = 0; toShow < nShips; toShow++)
            {
                btn = new Button(this);
                btn.setBackgroundResource(shipDrawable.get(ima));
                btn.setLayoutParams(params);
                row[pos].addView(btn);
                btn.setId(shipId.get(ima));
                btn.setOnClickListener(listeners);
                if (row[pos].getChildCount() == 3) pos++;
                ima++;
            }

我尝试在 for 循环中使用它:

float x = btn.getX(), y = btn.getY();
                TextView level = new TextView(this);
                level.setText("5");
                level.setX(x); level.setY(y);

但是没有用。我可以用什么来得到我想要的?

4

2 回答 2

2

如果要在 b 按钮上显示图像,则应为此使用 ImageButton。按钮和图像按钮之间的区别在于,在按钮中,您可以在按钮上显示文本,在 ImageButton 上,您可以在按钮上显示图像以及按钮的所有功能

于 2012-03-26T09:55:34.280 回答
2

KrLx_roller 我得到的很多是你想在一个按钮上放置文本,你不需要采取单独的文本视图,你可以像这样添加文本

    Button textOne = new Button(this);

    textOne.setText("5");
    textOne.setBackgroundResource(R.drawable.img);
    textOne.setGravity(Gravity.CENTER);
    textOne.setTextColor(Color.RED);
于 2012-03-26T10:51:14.680 回答