簡體   English   中英

如何在android中動態添加一個widget?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM