【发布时间】:2021-08-23 14:04:51
【问题描述】:
我想动态地将按钮小部件添加到线性布局,但它似乎不起作用。在我的 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);
【问题讨论】:
-
你的意思似乎不起作用。当你尝试时会发生什么?您的 xml 文件包含什么内容?