[英]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
. 我希望我动态创建的按钮打开一个新的
Activity
并通过Intent
传递此参数。 I am a .NET guy and this would be easily done with a CommandParameter
off of the Button
. 我是.NET专家,使用
Button
旁边的CommandParameter
可以轻松完成此操作。
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.
如果是这样,如何将命令参数传递给click事件。 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. 另外,最好使用foreach遍历列表,而不要使用while循环。
For adding a child to a TableLayout you need to add a TableRow, And also You need to add the LayoutParams to button. 要将子级添加到TableLayout中,您需要添加TableRow,还需要将LayoutParams添加到按钮。 Then add the button to the TableRow
然后将按钮添加到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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.