0

I am coming across an issue with dynamically creating buttons. I have my text I am adding to the buttons, however I also have a command argument I want to send with it. I want my dynamically created buttons to open up a new Activity and pass this argument via Intent. I am a .NET guy and this would be easily done with a CommandParameter off of the Button.

My question is, is this the following code best way to accomplish this task? If so, how can I pass command arguments to the click event. If not, what should be my approach?

int counter =0;

TableLayout layout = (TableLayout) findViewById(R.id.tableLayout);

while (counter< list.size())
{
    MyObj obj = list.get(counter);

    Button b = new Button(this);
    b.setText(obj.getName());   
    // CommandParameter = obj.getId().toString();

    b.setOnClickListener(new OnClickListener(){
        public void onClick(View v)
        {
            Context ctx = getApplicationContext(); 

            Intent intent = new Intent(ctx, TestScreen.class);
            intent.putExtra("Id", "MyCommandParameter");
            startActivity(intent) ;
        }
    });

    layout.addView(b);
    counter++;
}

2 Answers 2

1

Replace this line:

intent.putExtra("Id", "MyCommandParameter");

with

intent.putExtra("Id", obj.getId().toString());

Also, you are better off using a foreach to iterate through the list rather than while loop.

Sign up to request clarification or add additional context in comments.

1 Comment

I also had to add a final keyword for this to work, but this seems to solve my problem. (it wouldnt compile with out it) Thanks for pushing me in the right direction. I was unfamiliar with the final keyword, at least until I read up on it.
0

For adding a child to a TableLayout you need to add a TableRow, And also You need to add the LayoutParams to button. Then add the button to the TableRow

    TableRow tr = new TableRow(this);
               tr.setLayoutParams(new LayoutParams(
                              LayoutParams.FILL_PARENT,
                              LayoutParams.WRAP_CONTENT));
    Button b = new Button(this);
    b.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
    .....
    .....
tr.addView(b);

layout.addView(tr,new TableLayout.LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.