简体   繁体   中英

How to dynamically add buttons with a command argument for the OnClick Event

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++;
}

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.

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM