gpt4 book ai didi

java - 如何动态设置GridLayout中按钮的文本?

转载 作者:行者123 更新时间:2023-12-01 18:11:25 25 4
gpt4 key购买 nike

我尝试在每次迭代中使用 i 的值来为按钮设置文本。
正如您可能通过以下代码意识到的那样,我无法这样做。
你能帮我一下吗?

package com.example.sequenceofnumbers;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.GridLayout;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

GridLayout gl = findViewById(R.id.grid_layout);

for(int i = 1; i <= 16; i++) {
Button btn = new Button(this);
btn.setText(i+""); // I can't set text in this line.
}
}
}

最佳答案

package com.example.sequenceofnumbers;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.GridLayout;
import android.widget.Button; //Include this package.

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

GridLayout gl = findViewById(R.id.grid_layout);

for(int i = 1; i <= 16; i++) {
Button btn = new Button(this);
btn.setText(i+"");
gl.addView(btn); // Add this line instead.
}
}
}

关于java - 如何动态设置GridLayout中按钮的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60463834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com