簡體   English   中英

在Android Studio中動態添加和保存按鈕

[英]Dynamically Add and Save buttons in Android studio

目前,我設法在視圖上動態創建按鈕

這是我創建按鈕的代碼;

    public void Add_on(View v) {
        AlertDialog.Builder mbuilder = new AlertDialog.Builder(Mb.this);
        View mview = getLayoutInflater().inflate(R.layout.activity_mb1, null);
        EditText number = (EditText) mview.findViewById(R.id.etnum);
        Button Create = (Button) mview.findViewById(R.id.etcreate);
        Button Cancel = (Button) mview.findViewById(R.id.etcancel);

        Create.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){

                if (!number.getText().toString().isEmpty())
                {
                    Toast.makeText(Mb.this, "Number can be NULL",Toast.LENGTH_SHORT).show();


                    LinearLayout yenilayout = new LinearLayout(Mb.this);
                    int n =1;
                    for(int i=0; i<n; i++)
                    {
                        Button yeniButton = new Button(Mb.this);
                        yenilayout.addView(yeniButton);

                        yeniButton.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Toast.makeText(Mb.this, "Button is working",Toast.LENGTH_SHORT).show();
                            }
                        });

                    }
                    altlayout.addView(yenilayout);


                } else {
                    Toast.makeText(Mb.this, "Number cannot be NULL",Toast.LENGTH_SHORT).show();

                }

            }
        });

但是,每當我回憶起活動時,按鈕就不再存在。 所以我可以將按鈕永久放置在那里嗎?

謝謝你的建議

您可以使用Bundle保存活動的狀態,並在onCreate()方法中重新創建它。 這適用於Activity的特定實例,因此可以用於保存有關選擇或用戶輸入等的數據,但不能保存需要在應用程序啟動期間保持不變的數據。

要使用Bundle ,請覆蓋Activity類中的onSaveInstanceState(Bundle)onRestoreInstanceState(Bundle)方法。 您可以使用Bundle方法在地圖中保存所需的任何數據,然后將其取回onRestoreInstanceState(Bundle) ,該方法在onStart()onStart()

不過,默認實現已經可以處理大多數UI內容,並且我認為這可以為您跟蹤按鈕,因此,可能是您的問題實際上是有關將一些持久性數據與應用程序相關聯。 (這也意味着,如果您確實要覆蓋上述方法,則應確保在實現的第一行中調用super方法)。

如果您需要在應用程序啟動持久性數據,那么最快和最簡單的方法是使用SharedPreferences ,看到這個答案的一個例子。

暫無
暫無

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

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