【问题标题】:How do I add these buttons to my main activity? [duplicate]如何将这些按钮添加到我的主要活动中? [复制]
【发布时间】:2019-06-08 05:15:33
【问题描述】:

我制作了一些按钮并将它们存储到一个 ArrayList 中。我需要将这些按钮添加到我的主要活动布局中。

我尝试创建一个线性布局并将其作为我的主要布局,但是按钮不显示。

   public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
 // createButtons();setContentView(new CircleView(this));



}

public void createButtons() {


    ArrayList<Button> buttons = new ArrayList<>();

    int n = 0; // the number of buttons circumferencing the semicircle
    for(int i = 0; i < 6; i ++) {
        n = 7;
        Button button = new Button(this);
        double Xval = 500* Math.cos(i * Math.PI / n);
        double Yval = 500* Math.sin(i * Math.PI / n);
        button.setX((float)(Xval));
        button.setY((float)(Yval));

        buttons.add(button);

    }



}
}

我希望我的按钮出现在我的主要活动布局中。

【问题讨论】:

  • 你没有在布局中添加按钮
  • 如何将按钮添加到布局中?
  • 在你问这个问题之前我已经链接了这个问题

标签: java android


【解决方案1】:

我为您的情况找到了一些解决方案,但不是正确的解决方案,您必须将其更改为您自己的实现。

执行此操作的一种方法是创建一个布局并通过 id 在代码中获取布局,然后插入按钮。这是执行此操作的一种方法:

Button myButton = new Button(this);
myButton.setText("Push Me");

LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);

使用事件插入多个按钮,即使我更喜欢在类上实现 OnClickListener:

for (int i = 1; i <= 20; i++) {
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    Button btn = new Button(this);
    btn.setId(i);
    final int id_ = btn.getId();
    btn.setText("button " + id_);
    btn.setBackgroundColor(Color.rgb(70, 80, 90));
    linear.addView(btn, params);
    btn1 = ((Button) findViewById(id_));
    btn1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Toast.makeText(view.getContext(),
                    "Button clicked index = " + id_, Toast.LENGTH_SHORT)
                    .show();
        }
    });
}

你可以在链接Android Samples找到很多android native的示例

Source

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多