【问题标题】:How to dynamically add a widget in android?如何在android中动态添加小部件?
【发布时间】: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 文件包含什么内容?

标签: java android xml widget


【解决方案1】:

你在正确的轨道上,但问题是你的颜色参数。

 button.setText("I am added");
 button.setTextColor(Color.BLACK);
 button.setBackgroundColor(Color.MAGENTA);

尝试使用颜色类常量,就像我在上面所做的那样。

//You don't need this
button.setId(R.id.added_btn_1);

也不要在按钮上添加设置 ID,因为您没有将其添加到视图层次结构中。名称标识符就足够了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多