如何在运行时创建多个按钮? +安卓 [英] How to create multiple buttons at runtime? + android

查看:123
本文介绍了如何在运行时创建多个按钮? +安卓的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面code,但我没有得到如何写 OnclickListner()方法,所有按钮。

 公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);
    的LinearLayout布局=(的LinearLayout)findViewById(R.id.ll1Relative);
    的for(int i = 1;我小于10;我++){
        LinearLayout.LayoutParams P =新LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        );
        按钮B =新的按钮(这一点);
        b.setText(+ I);
        b.setId(100 + I);
        b.setWidth(30);
        b.setHeight(20);
        layout.addView(B,P);
    }
}
 

解决方案

您可以使用匿名内部方法是这样的:

 按钮B =新的按钮(这一点);
b.setOnClickListener(新OnClickListener(){
    公共无效的onClick(视图v){
        //执行上的点击动作
    }
});
b.setText(+ I);
b.setTag(按钮+ I);
b.setWidth(30);
b.setHeight(20);
 

I wrote the following code but am not getting how to write OnclickListner() method for all buttons.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    LinearLayout layout = (LinearLayout) findViewById(R.id.ll1Relative);
    for (int i = 1; i < 10; i++) {
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        );
        Button b = new Button(this);
        b.setText(""+ i);
        b.setId(100+i);
        b.setWidth(30);
        b.setHeight(20);
        layout.addView(b, p);
    }
}

解决方案

You can use an anonymous inner method like this:

Button b = new Button(this);
b.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        // Perform action on click
    }
});
b.setText("" + i);
b.setTag("button" + i);
b.setWidth(30);
b.setHeight(20);

这篇关于如何在运行时创建多个按钮? +安卓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆