如何获取方法中启动的计数器值

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() 被调用,那么 activity 将不会被 Android 重新启动,并且您不需要保存 activity 的实例来恢复它.但是要小心,从文档

Remember: When you declare your activity to handle a configuration change, you are responsible for resetting any elements for which you provide alternatives. If you declare your activity to handle the orientation change and have images that should change between landscape and portrait, you must re-assign each resource to each element during onConfigurationChanged().

counter 变量是全局变量,因此您可以从 onConfigurationChanged() 方法访问它,并且当屏幕方向改变时变量的值将被保留,因为 Android 不会重新启动 activity。您可以像在 onFloatActionButtonClick(...) 方法

中一样访问它
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

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

使用onConfigurationChanged() 将保留在运行时添加的activity 实例和视图(例如,按下按钮时添加的视图)。如果你想通过重新启动 activity 来获得相同的结果,你需要保存 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