DYNAMICALLY CREATED BUTTON TEXT ACQUISITION METHOD

Asked 2 years ago, Updated 2 years ago, 77 views

I would like to implement the process of retrieving the text of the button created in the for statement.
I would like to identify the button I clicked when selecting the button without using id, is there any way?
Also, please let me know if there are any recommended methods for the respondents.
There may be some deficiencies in the code, but please let me know when you do.

private Button [] = new Button [20];

for(inti=0,j=0;i<button.length;i++,j++){

    button[i] = new Button(this);
    // Configure Tag
    button[i].setText(data2[1][i]); // Set a string that already exists
    button[i].setId(i);
    button[i].setOnClickListener(newOnClickListener(){
         public void onClick (View view) {

              // I want to write the processing here

         }
    });
    LinearLayout.LayoutParams buttonLayoutParams=new 
    LinearLayout.LayoutParams(
                buttonWidth, ViewGroup.LayoutParams.WRAP_CONTENT);
        buttonLayoutParams.setMargins(margins, margins, margins);

        button[i].setLayoutParams(buttonLayoutParams);
        layout.addView (button[i]);
}

android android-studio

2022-09-30 16:07

1 Answers

In this case, you can only call getText() because the View has already been retrieved.

public void onClick(View view){
          Log.d("test", "text is" + ((Button) view).getText());
     }


2022-09-30 16:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.