Android 以编程方式创建按钮,并使用listener从第一个按钮创建下一个按钮
我在想这件奇怪的事。我想创建一个按钮,当按钮被点击时,我想创建一个新的按钮,删除旧的按钮,所有这些都只需要代码 这是到目前为止我的代码,它并没有像我希望的那样工作。 有什么意见吗?谢谢Android 以编程方式创建按钮,并使用listener从第一个按钮创建下一个按钮,android,button,onclicklistener,programmatically-created,Android,Button,Onclicklistener,Programmatically Created,我在想这件奇怪的事。我想创建一个按钮,当按钮被点击时,我想创建一个新的按钮,删除旧的按钮,所有这些都只需要代码 这是到目前为止我的代码,它并没有像我希望的那样工作。 有什么意见吗?谢谢 public void createRounds(int rounds){ ArrayList<Button> buttonArray = new ArrayList<>(); for(int i=0;i<=rounds;i++){ bk =
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);
}
});
}
}
public void createRounds(整数轮){
ArrayList buttonArray=新的ArrayList();
对于(int i=0;i我创建了示例代码来回答我对您的问题的理解,请参见下面使用XML和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();
}
}
}
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>
也许你可以更改它的id?并创建一个全局onclicklistener,然后你可以按照你的计划在你的listener上执行任何你想做的事情。这就成功了。现在我只需添加一些额外的内容。非常感谢