0

每次单击floatactionbutton时,我的应用程序会动态创建(最多)8个按钮,但是当屏幕旋转时,所有按钮都会消失。我知道这背后的原因,那是因为我没有在生成的视图上设置 onSaveInstanceState。我尝试使用 outState.putInt 设置 onSaveInstanceState (因为我觉得这是合适的,因为按钮 ID 是 int 类型)但它不起作用。

这是我的Java。

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 void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        outState.putInt("semesterButton", semesterButton.getId());
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        savedInstanceState.getInt("semesterButton", semesterButton.getId());
        super.onRestoreInstanceState(savedInstanceState);
    }

    @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);

            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);
            }

            // these lines moved outside the if statement blocks
            counter++;
            setOnLongClickListenerForSemesterButton();

        } else if (counter == 8) {
            Toast.makeText(MainActivity.this, "You cannot add more than 8 semesters", 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;
            }
        });
    }
}

更新: 对于我的 onSaveInstaceState,我这样做了:

@Override
    public void onSaveInstanceState(Bundle outsave) {
        super.onSaveInstanceState(outsave);

        if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
            outsave.putInt("NUMBEROFBUTTONS", semesterGridLayout.getChildCount());
        } else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
            outsave.putInt("NUMBEROFBUTTONS", semesterLayout.getChildCount());
        }

    }

对于我的 onCreate,这就是我所做的:

 @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) {
            int numberofbuttons = savedInstanceState.getInt("NUMBEROFBUTTONS");

            if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
                for(int i = 0; i < numberofbuttons; i++){
                    semesterLayout.addView(semesterButton);
                }
            } else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
                for(int i = 0; i < numberofbuttons; i++){
                    semesterGridLayout.addView(semesterButton);

                }
            }
        }

    }

这是我在堆栈跟踪中遇到的问题

FATAL EXCEPTION: main
                                                                                 Process: myapp.onur.journeygpacalculator, PID: 10463
                                                                                 java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.GridLayout.getChildCount()' on a null object reference
                                                                                     at myapp.onur.journeygpacalculator.MainActivity.onSaveInstanceState(MainActivity.java:68)

基本上问题是我无法为我的 GridLayout 对象获取 getChildCount() 。

4

1 回答 1

0

您无法在配置更改之间保存与 UI 相关的变量(旋转屏幕时会发生这种情况)。

但是,您有多种选择来做您想做的事:

您可以使用片段。如果您在按钮片段上使用“setRetainInstance”,它应该在配置更改之间保持不变,但是这种方法不允许您处理 backstack(用于使用返回按钮恢复更改)。亲:最简单的处理方式。缺点:嗯,setRetainInstance 用于保存没有 UI 元素的片段。

您可以在编写时将按钮的数量保存在 onSaveInstanceState 中,但是您需要检查“onCreate”上的捆绑包,如果不为空,则获取数字并相应地添加按钮。亲:容易。缺点:如果你从按钮切换到任何东西,或者如果按钮依赖于一些外部数据,这样做可能会改变你的按钮外观。

您可以自己管理屏幕旋转。我不知道该怎么做,但我不推荐该选项,因为如果用户交换语言、区域或任何导致配置更改的内容,问题仍然存在。但是,即使这是最糟糕的(IMO),也需要提及此选项。

编辑:根据要求提供有关第二个的更多详细信息->

首先,覆盖onSaveInstanceState

public void onSaveInstanceState(Bundle outsave) {
    super.onSaveInstanceState(outsave);
    outsave.putInt("NUMBEROFBUTTONS", number_of_buttons);
}

然后,在 onCreate 期间:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(savedInstanceState!=null) {
        int number_of_button = savedInstanceState.getInt("NUMBEROFBUTTONS");
        display_X_buttons(number_of_button); /*sum up : display number_of_button buttons as you wish display them.*/
    }
}
于 2017-04-21T00:09:19.647 回答