以编程方式创建按钮并使用侦听器从第一个按钮创建下一个按钮

Create button programmatically and create next button from the first button with listener

我想知道这件奇怪的事。我想创建一个按钮,当单击该按钮时,我想创建一个新按钮并删除旧按钮,所有这些都只有代码。

到目前为止,这是我的代码,它没有像我希望的那样工作。 这里有什么输入吗?谢谢

    public void createRounds(int rounds){
    ArrayList<Button> buttonArray = new ArrayList<>();
    for(int i=0;i<=rounds;i++){
        bk = new Button(getActivity());
        bk.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
        bk.setBackground(getResources().getDrawable(R.drawable.btnshapegreen));
        bk.setId(i);
        bk.setText("Button "+i);
        buttonArray.add(bk);
    }
    for(final Button a : buttonArray){
            generated_time.addView(a);
            a.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(getActivity(),a.getText().toString(),Toast.LENGTH_LONG).show();
                    generated_time.removeView(a);
                }
            });
    }
}

I know that the for-each loop does add all buttons at once, but isnt there a way to add one at a time?

我创建了示例代码来回答我对您的问题的理解,请参阅下面的代码 XMLJAVA

XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</android.support.constraint.ConstraintLayout>

JAVA

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private int id = 0;
    private Button button;
    private ConstraintLayout layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        layout = findViewById(R.id.container);
        button = new Button(this);
        button.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        button.setId(id);
        button.setText(String.format("%d", id));
        button.setOnClickListener(this);
        layout.addView(button);
        layout.requestLayout();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == id) {
            id++;
            button.setId(id);
            button.setText(String.format("%d", id));
            layout.requestLayout();
        }
    }
}