Dynamically creating Buttons and setting onClickListener

后端 未结 9 1000
囚心锁ツ
囚心锁ツ 2020-11-29 22:45

I have problem with handling dynamically created Buttons on Android. I\'m creating N buttons and I have to do the same method when button is clicked but I have to know which

9条回答
  •  渐次进展
    2020-11-29 23:00

    I got one solution for this.. use this code in onCreate

    linear = (LinearLayout) findViewById(R.id.linear);
    
    LayoutParams param = new LinearLayout.LayoutParams(
    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f);
    
    Button[] btn = new Button[num_array_name.length];
    for (int i = 0; i < num_array_name.length; i++) {
        btn[i] = new Button(getApplicationContext());
        btn[i].setText(num_array_name[i].toString());
        btn[i].setTextColor(Color.parseColor("#000000"));
        btn[i].setTextSize(20);
        btn[i].setHeight(100);
        btn[i].setLayoutParams(param);
        btn[i].setPadding(15, 5, 15, 5);
        linear.addView(btn[i]);
    
        btn[i].setOnClickListener(handleOnClick(btn[i]));
    
    }
    

    after onCreate create one method of return type View.OnClickListener like this..

    View.OnClickListener handleOnClick(final Button button) {
        return new View.OnClickListener() {
            public void onClick(View v) {
            }
        };
    }
    

提交回复
热议问题