01.
public
class
MainActivity
extends
Activity {
02.
03.
@Override
04.
protected
void
onCreate(Bundle savedInstanceState) {
05.
super
.onCreate(savedInstanceState);
06.
setContentView(R.layout.dynamically_create_view_element);
07.
08.
final
LinearLayout lm = (LinearLayout) findViewById(R.id.linearMain);
09.
10.
11.
12.
LinearLayout.LayoutParams params =
new
LinearLayout.LayoutParams(
13.
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
14.
15.
16.
for
(
int
j=
0
;j<=
4
;j++)
17.
{
18.
19.
LinearLayout ll =
new
LinearLayout(
this
);
20.
ll.setOrientation(LinearLayout.HORIZONTAL);
21.
22.
23.
TextView product =
new
TextView(
this
);
24.
product.setText(
" Product"
+j+
" "
);
25.
ll.addView(product);
26.
27.
28.
TextView price =
new
TextView(
this
);
29.
price.setText(
" $"
+j+
" "
);
30.
ll.addView(price);
31.
32.
33.
final
Button btn =
new
Button(
this
);
34.
35.
btn.setId(j+
1
);
36.
btn.setText(
"Add To Cart"
);
37.
38.
btn.setLayoutParams(params);
39.
40.
final
int
index = j;
41.
42.
btn.setOnClickListener(
new
OnClickListener() {
43.
public
void
onClick(View v) {
44.
45.
Log.i(
"TAG"
,
"index :"
+ index);
46.
47.
Toast.makeText(getApplicationContext(),
48.
"Clicked Button Index :"
+ index,
49.
Toast.LENGTH_LONG).show();
50.
51.
}
52.
});
53.
54.
55.
ll.addView(btn);
56.
57.
lm.addView(ll);
58.
}
59.
}
60.
}