簡體   English   中英

如何獲取方法中啟動的計數器值

[英]How to get the counter value that is initiated in a method

我正在構建一個動態生成按鈕的應用程序。 通過onSaveInstanceState保存按鈕不起作用,因為我不能通過該方法保存UI元素,因此最有意義的選項是根據方向更改重新創建視圖。 我確切地知道該怎么做(重寫onConfigurationChanged方法),但是我的問題是我無法獲得當前的計數器值。 計數器變量是全局變量,但未初始化。 它在onFloatActionButtonClick內部遞增,以檢查我添加了多少按鈕,但是我無法從onConfigurationChanged方法訪問該內部值來重新創建相同數量的通過方向更改而被破壞的按鈕。

感謝所有幫助。

public class MainActivity extends AppCompatActivity {

    int counter = 0;

    FloatingActionButton addingSemester;
    Button semesterButton;
    LinearLayout semesterLayout;
    GridLayout semesterGridLayout;

    LinearLayout.LayoutParams portraitLayoutParams = new LinearLayout.LayoutParams(
            AppBarLayout.LayoutParams.MATCH_PARENT,
            AppBarLayout.LayoutParams.WRAP_CONTENT);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addingSemester = (FloatingActionButton) findViewById(R.id.addActionButton);
        semesterLayout = (LinearLayout) findViewById(R.id.main_layout);

        semesterGridLayout = (GridLayout)findViewById(R.id.semester_grid_layout);

        semesterButton = new Button(MainActivity.this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

            if (id == R.id.delete) {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("Delete entry")
                        .setMessage("Are you sure you want to delete everything?")
                        .setCancelable(true)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
                                    semesterGridLayout.removeAllViews();
                                } else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
                                    semesterLayout.removeAllViews();
                                }
                                counter = 0;
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        })
                        .show();
                return true;
            }


        return super.onOptionsItemSelected(item);

    }

    public void onFloatActionButtonClick(View view) {
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);

        double width = (size.x)/3;

        semesterButton = new Button(MainActivity.this);
        if (counter < 8) {
            semesterButton.setId(counter + 1);
            semesterButton.setText("Semester " + (counter + 1));
            semesterButton.setBackgroundColor(getColor(R.color.colorPrimary));
            semesterButton.setTextColor(Color.WHITE);
            portraitLayoutParams.setMargins(24, 24, 24, 24); // keep this line

            if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
                GridLayout.LayoutParams params = new GridLayout.LayoutParams();
                params.setMargins(24, 24, 24, 24);
                params.width = (int) width;
                params.height = GridLayout.LayoutParams.WRAP_CONTENT;
                semesterButton.setLayoutParams(params);
                semesterGridLayout.addView(semesterButton);
            } else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
                semesterLayout.addView(semesterButton);
                semesterButton.setLayoutParams(portraitLayoutParams); // keep this line
            }

            counter++;
            setOnLongClickListenerForSemesterButton();

        } else if (counter == 8) {
            Toast.makeText(MainActivity.this, "You cannot add more than 8 semesters", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);


        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            Toast.makeText(MainActivity.this,"Screen is in Orientation", Toast.LENGTH_SHORT).show();
        }
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Toast.makeText(MainActivity.this, "Screen is in Landscape", Toast.LENGTH_SHORT).show();
        }
    }

    private void setOnLongClickListenerForSemesterButton() {
        semesterButton.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                final Button b = (Button) v;
                b.setTag(b.getText().toString());
                b.setBackgroundColor(Color.RED);
                b.setText("Delete");

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle("Delete entry");
                        builder.setMessage("Are you sure you want to delete this entry?");
                        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
                                    semesterGridLayout.removeView(b);
                                    for (int i = 0; i < semesterGridLayout.getChildCount(); i++) {
                                        ((Button) semesterGridLayout.getChildAt(i)).setText("Semester " + (i + 1));
                                    }
                                } else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
                                    semesterLayout.removeView(b);
                                    for (int i = 0; i < semesterLayout.getChildCount(); i++) {
                                        ((Button) semesterLayout.getChildAt(i)).setText("Semester " + (i + 1));
                                    }
                                }
                                counter--;
                            }
                        });
                        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                b.cancelLongPress();
                                b.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
                                b.setText(b.getTag().toString());
                                dialog.cancel();

                            }
                        });
                        builder.show();
                return true;
            }
        });
    }
}

編輯

這是我在沒有視圖時試圖隱藏我的MenuItem的地方。

@Override
    public boolean onOptionsItemSelected(MenuItem item) {

        Configuration newConfig = new Configuration();

        if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            if(semesterLayout.getChildCount() == 0){
                item.setVisible(false);
            }
        }

        if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
            if (semesterGridLayout.getChildCount() == 0){
                item.setVisible(false);
            }
        }

        int id = item.getItemId();

            if (id == R.id.delete) {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("Delete entry")
                        .setMessage("Are you sure you want to delete everything?")
                        .setCancelable(true)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
                                    semesterGridLayout.removeAllViews();
                                } else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
                                    semesterLayout.removeAllViews();
                                }
                                counter = 0;
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        })
                        .show();
                return true;
            }


        return super.onOptionsItemSelected(item);

    }

如果onConfigurationChanged()則Android將不會重新啟動活動,並且您無需保存活動實例即可將其還原。 但是要小心,從文檔中

切記:聲明要處理配置更改的活動時,您有責任重置所有為其提供替代方案的元素。 如果聲明要處理方向變化的活動,並且圖像應在橫向和縱向之間改變,則必須在onConfigurationChanged()期間將每個資源重新分配給每個元素。

counter變量是全局變量,因此您可以從onConfigurationChanged()方法訪問它,並且當屏幕方向更改時,該變量的值將被保留,因為Android不會重新啟動活動。 您可以像在onFloatActionButtonClick(...)方法中一樣進行訪問

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    System.out.println(counter); //Print the counter value
}

使用onConfigurationChanged()將保留活動實例和在運行時添加的視圖(例如,在按下按鈕時添加視圖)。 如果要通過重新啟動活動來獲得相同的結果,則需要保存counter值,然后必須在onCreate方法中還原counter值並基於該值重新填充布局。

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the counter value
    savedInstanceState.putInt("counter", counter);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    addingSemester = (FloatingActionButton) findViewById(R.id.addActionButton);
    semesterLayout = (LinearLayout) findViewById(R.id.main_layout);

    semesterGridLayout = (GridLayout)findViewById(R.id.semester_grid_layout);

    semesterButton = new Button(MainActivity.this);

    if (savedInstanceState != null) {
        // Restore the counter value
        counter = savedInstanceState.getInt("counter");

        //Repopulate the layout
        for(int i = 0; i < counter; i++) {
            addSemesterButton(i);
        }
    }
}

public void addSemesterButton(int id) {
    //This is an edited version of onFloatActionButtonClick(...) method
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);

    double width = (size.x)/3;

    semesterButton = new Button(MainActivity.this);
    semesterButton.setId(id + 1);
    semesterButton.setText("Semester " + (id + 1));
    semesterButton.setBackgroundColor(getColor(R.color.colorPrimary));
    semesterButton.setTextColor(Color.WHITE);
    portraitLayoutParams.setMargins(24, 24, 24, 24); // keep this line

    if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
        GridLayout.LayoutParams params = new GridLayout.LayoutParams();
        params.setMargins(24, 24, 24, 24);
        params.width = (int) width;
        params.height = GridLayout.LayoutParams.WRAP_CONTENT;
        semesterButton.setLayoutParams(params);
        semesterGridLayout.addView(semesterButton);
    } else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
        semesterLayout.addView(semesterButton);
        semesterButton.setLayoutParams(portraitLayoutParams); // keep this line
    }
}

有關更多信息, 參見https://developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange

暫無
暫無

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

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