簡體   English   中英

添加第一個按鈕后,無法在Android中動態添加按鈕

[英]Dynamically adding Buttons in Android doesn't work after the first Button is added

我有一個用代碼創建的按鈕,該按鈕具有Click事件的偵聽器。 每次單擊該按鈕時,它都應生成另一個按鈕並將其添加到原始按鈕下方。 但是,無論我單擊第一個按鈕多少次,它只會添加一次動態按鈕,而不再添加任何按鈕。

這是我的編碼:

public class DynaminControlActivity extends Activity {
    private RelativeLayout container;
    private int mainIdCnt = 0;
    private int mainId = 100;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        createMainButton();
    }

    public void createMainButton() {
        container = (RelativeLayout) findViewById(R.id.workLayout);
        Button b = new Button(this);
        b.setId(mainIdCnt + mainId);
        CharSequence text = "Main +";
        b.setText(text);
        container.addView(b);
        if (mainId > 0) {
            mainId++;
        }
        b.setOnClickListener((new View.OnClickListener() {
            public void onClick(View v) {
                createDynamicButton();
            }
        }));
    }

    public void createDynamicButton() {
        container = (RelativeLayout) findViewById(R.id.workLayout);
        Button b = new Button(this);
        CharSequence text = "Main +";
        b.setText(text);
        RelativeLayout.LayoutParams relLayout = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        relLayout.addRule(RelativeLayout.BELOW, mainIdCnt + mainId);
        container.addView(b, relLayout);
        if (mainId > 0) {
            mainId++;
        }
    }

一些東西...

  1. 如果您的主要布局是LinearLayout,則無需添加規則來指示該按鈕應出現在現有按鈕的下方-它會自動添加到的最底部(垂直對齊)或最右側(水平對齊)布局。

  2. 您所有的按鈕都有相同的文本。 您確定每次都單擊第一個按鈕嗎? 我注意到,只有第一個按鈕上有一個偵聽器,因此,如果您不小心單擊了其他按鈕之一,則不會發生任何事情。

  3. 如果您打算添加多個按鈕,它將迅速擴展到大於屏幕尺寸,因此您應確保主布局位於ScrollView中,以便可以看到添加的所有按鈕。

  4. 對setId()的調用可能充斥着Android的內部工作原理。 除了設置ID外,您還應該讓Android自動生成ID,並在需要引用該值時檢索該值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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