Question

I am creating Layout dynamically with 10 buttons with 10 ids. Like this:

    private Button myButton;
private TextView wynik;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    createLayoutDynamically();
    score = (TextView) findViewById(R.id.textView2);

        }

private void createLayoutDynamically() {

    int a = 10;
    for ( int q = 1; q < a; q++) {
         myButton = new Button(this);
        myButton.setText("q:"+q);
        myButton.setId(q);

        TableRow layout = (TableRow) findViewById(R.id.tableRow1);

        layout.addView(myButton);

    }   
        }

    }

Now i want to get this ids from my 10 buttons only when i click on button and put as integer into textView "score" and then sum these integers.

for example: q:1 q:2 q:3 q:4 q:5 are buttons when I click q:1 and q:3 and q:4 i want sum value of these buttons.

1+3+4=8.

Was it helpful?

Solution

I don't think you should use the ids for this as that is not what its for. I think that you should use the tag property instead, and you will need a click listener for when the button is clicked.

private void createLayoutDynamically() {

int a = 10;
for ( int q = 1; q < a; q++) {
     myButton = new Button(this);
    myButton.setText("q:"+q);
    myButton.setId(q);

    myButton.setTag(q);
    myButton.setOnClickListener(listener);

    TableRow layout = (TableRow) findViewById(R.id.tableRow1);

    layout.addView(myButton);

}   
}

Declare a variable at the class level:

private int total;

And then when you click on the button:

Private OnClickListener listener = new OnClickListener()
{
    public void onClick(View v)
    {
         int buttonValue = (int)v.getTag();
         total += buttonValue;
         myTextView.setText(String.valueOf(total));
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top