【问题标题】:How to add button to layout at runtime如何在运行时将按钮添加到布局
【发布时间】:2016-07-25 05:49:27
【问题描述】:

我想在创建按钮时将它们一个一个地动态添加到网格布局中,但在我的情况下,按钮是通过每次迭代一个一个地创建的,但是当循环迭代完成时它们会立即添加到布局中。
// 这里是代码...

 public void Add_Button(View view){
        final MediaPlayer mediaPlayer=MediaPlayer.create(getApplicationContext(),R.raw.button_sound);
        gridlayout= (GridLayout) findViewById(R.id.layout);
        animation= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.scale_button);
        for(int i=0;i<10;i++) {
            Button button = new Button(MainActivity.this);
            button.setText(i+1 + "");
            button.setPadding(10,10,10,10);
            GridLayout.LayoutParams params = new GridLayout.LayoutParams();
            params.height=70;
            params.width=70;
            params.topMargin = 10;
            params.leftMargin = 10;
              *//after one 1 second i want to add button*
            try {
                Thread.sleep(1000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            button.setLayoutParams(params);
            button.setAnimation(animation);
            mediaPlayer.start();
            gridlayout.addView(button);
        }

        }

【问题讨论】:

  • 你的问题不清楚。使用当前代码有什么问题?
  • 检查此stackoverflow.com/questions/13532084/… 可能会有所帮助
  • 你不应该仅仅为了实现一个简单的动画而暂停主线程。

标签: android android-layout


【解决方案1】:

你可以这样添加

LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
layout.setOrientation(LinearLayout.VERTICAL);  //Can also be done in xml by android:orientation="vertical"

for (int i = 0; i < 3; i++) {
    LinearLayout row = new LinearLayout(this);
    row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

    for (int j = 0; j < 4; j++ {
        Button btnTag = new Button(this);
        btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        btnTag.setText("Button " + (j + 1 + (i * 4));
        btnTag.setId(j + 1 + (i * 4));
        row.addView(btnTag);
    }

    layout.addView(row);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多