[英]How to dynamically add a widget in android?
我想动态地将按钮小部件添加到线性布局,但它似乎不起作用。 在我的 sum_example.xml 文件中,我已经在作为根布局的线性布局中添加了三个小部件。
//Finding the layout
LinearLayout linear = (LinearLayout) findViewById(R.id.sum_example_root);
//Creating a widget
Button button = new Button(this);
//Setting the required parameters of widget
button.setLayoutParams(new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
//Setting optional parameters of widget
button.setId(R.id.added_btn_1);
button.setText("I am added");
button.setTextColor(0x000000);
button.setBackgroundColor(0x00ff00);
button.setOnClickListener(this::sum);
//Adding the widget to the layout
linear.addView(button);
您走在正确的轨道上,但问题是您的 Colors arguments。
button.setText("I am added");
button.setTextColor(Color.BLACK);
button.setBackgroundColor(Color.MAGENTA);
尝试使用 Color Class Constants 代替我在上面所做的。
//You don't need this
button.setId(R.id.added_btn_1);
也不要在按钮上添加设置 Id,因为您没有将它添加到视图层次结构中。 名称标识符应该足够了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.