如何获取方法

时间:2017-04-24 00:21:09

标签: java android onconfigurationchanged

我正在构建一个动态生成按钮的应用程序。通过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);

    }

1 个答案:

答案 0 :(得分:0)

如果调用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