简体   繁体   English

没有视图时尝试隐藏菜单项

[英]Trying to hide the menu item when there are no views

I'm trying to build an app that generates buttons dynamically per floatActionButton click. 我正在尝试构建一个应用程序,该应用程序每次floatActionButton单击都会动态生成按钮。 This aspect works fine. 这方面工作正常。 But if there are no views, there shouldn't be a delete menu item on the action bar. 但是,如果没有视图,则操作栏上不应有删除菜单项。 At the start of the app, since there are no items, there is no menu item but I need the menu item to show up once I start adding views. 在应用程序启动时,由于没有项目,因此没有菜单项,但是一旦开始添加视图,我就需要显示菜单项。 I tried to work it with if statements but it still did not work. 我尝试使用if语句处理它,但是它仍然不起作用。

This is my code: 这是我的代码:

public class MainActivity extends AppCompatActivity {

    int counter = 0;

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

    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);
        GridLayout.LayoutParams params = new GridLayout.LayoutParams();

        relativeLayout = (RelativeLayout)findViewById(R.id.relativeLayout);

        semesterButton = new Button(MainActivity.this);

        if (savedInstanceState != null) {
            counter = savedInstanceState.getInt("counter");

            for(int i = 0; i < counter; i++) {
                addSemesterButton(i);
            }
        }
    }

    public void addSemesterButton(int id) {
        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);

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

        setOnLongClickListenerForSemesterButton();
    }

    public void addTextView(int id){
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);

        double width = (size.x);

        TextView instructionsPromptTextView = new TextView(MainActivity.this);
        instructionsPromptTextView.setId(id);
        instructionsPromptTextView.setText(R.string.click_the_button_to_add_semesters);
        instructionsPromptTextView.setTextSize((float)width);
        instructionsPromptTextView.setVisibility(View.VISIBLE);
        instructionsPromptTextView.setBackgroundColor(Color.BLACK);
        relativeLayout.addView(instructionsPromptTextView);


        if(id == 0){
            instructionsPromptTextView.setVisibility(View.INVISIBLE);
        }

    }

    public void onFloatActionButtonClick(View view) {
        if (counter < 8) {
            addSemesterButton(counter);

            counter++;
            setOnLongClickListenerForSemesterButton();

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem item = menu.findItem(R.id.delete);
        if(counter == 0){
            item.setVisible(false);
        }

        if(counter > 0){
            MenuInflater menuInflater = getMenuInflater();
            menuInflater.inflate(R.menu.main, menu);
            item.setVisible(true);
        }

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

    }


    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        savedInstanceState.putInt("counter", counter);
        super.onSaveInstanceState(savedInstanceState);
    }

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

EDIT 编辑

This is the stacktrace 这是堆栈跟踪

FATAL EXCEPTION: main
                                                                                 Process: myapp.onur.journeygpacalculator, PID: 22605
                                                                                 java.lang.IllegalStateException: Could not execute method for android:onClick
                                                                                     at android.view.View$DeclaredOnClickListener.onClick(View.java:4711)
                                                                                     at android.view.View.performClick(View.java:5623)
                                                                                     at android.view.View$PerformClick.run(View.java:22433)
                                                                                     at android.os.Handler.handleCallback(Handler.java:751)
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                     at android.os.Looper.loop(Looper.java:154)
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:6247)
                                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
                                                                                  Caused by: java.lang.reflect.InvocationTargetException
                                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                                     at android.view.View$DeclaredOnClickListener.onClick(View.java:4706)
                                                                                     at android.view.View.performClick(View.java:5623) 
                                                                                     at android.view.View$PerformClick.run(View.java:22433) 
                                                                                     at android.os.Handler.handleCallback(Handler.java:751) 
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                                                     at android.os.Looper.loop(Looper.java:154) 
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:6247) 
                                                                                     at java.lang.reflect.Method.invoke(Native Method) 
                                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872) 
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762) 
                                                                                  Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.add(int, int, int, java.lang.CharSequence)' on a null object reference
                                                                                     at android.view.MenuInflater$MenuState.addItem(MenuInflater.java:493)
                                                                                     at android.view.MenuInflater.parseMenu(MenuInflater.java:190)
                                                                                     at android.view.MenuInflater.inflate(MenuInflater.java:111)
                                                                                     at android.support.v7.view.SupportMenuInflater.inflate(SupportMenuInflater.java:113)
                                                                                     at myapp.onur.journeygpacalculator.MainActivity.inflateMenu(MainActivity.java:182)
                                                                                     at myapp.onur.journeygpacalculator.MainActivity.onFloatActionButtonClick(MainActivity.java:168)

Instead of setting it invisible only in onCreateOptionsMenu set it in your action button click too like below 而不是仅在onCreateOptionsMenu中将其设置为不可见,而不是在操作按钮中将其设置为如下所示

    MenuItem item;

    @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater menuInflater = getMenuInflater();
            menuInflater.inflate(R.menu.main, menu);
            item = menu.findItem(R.id.delete);
            item.setVisible(false);

            return super.onCreateOptionsMenu(menu);
        }


        public void onFloatActionButtonClick(View view) {
            if (counter < 8) {
                addSemesterButton(counter);

                counter++;
                setOnLongClickListenerForSemesterButton();
                item.setVisible(true);

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

1. Update onCreateOptionsMenu() as below, to hide delete option when app starts first: 1.如下更新onCreateOptionsMenu() ,以在应用程序首次启动时隐藏delete选项:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);

    itemDelete = menu.findItem(R.id.delete);

    // Required to hide delete option when app starts first
    itemDelete.setVisible(false); 

    return true;
}

2. Add below method to update the state of delete option. 2.添加以下方法以update delete选项的状态。

    public void updateOptionMenu() {
        if (counter > 0) 
            item.setVisible(true);
        else
            item.setVisible(false);    
    }

3. Call updateOptionMenu() method from all places where the counter value changes like: onFloatActionButtonClick() and AlertDialog's onClick() methods. 3.counter值发生变化的所有位置调用updateOptionMenu()方法,例如: onFloatActionButtonClick()AlertDialog's onClick()方法。

Here is the full code: 这是完整的代码:

public class MainActivity extends AppCompatActivity {


    MenuItem itemDelete;
    int counter = 0;

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

    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);
        GridLayout.LayoutParams params = new GridLayout.LayoutParams();

        relativeLayout = (RelativeLayout)findViewById(R.id.relativeLayout);

        semesterButton = new Button(MainActivity.this);

        if (savedInstanceState != null) {
            counter = savedInstanceState.getInt("counter");

            for(int i = 0; i < counter; i++) {
                addSemesterButton(i);
            }
        }

        addTextView(counter);
    }

    public void addSemesterButton(int id) {
        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);

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

        setOnLongClickListenerForSemesterButton();
    }

    public void addTextView(int id){
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);

        double width = (size.x);

        TextView instructionsPromptTextView = new TextView(MainActivity.this);
        instructionsPromptTextView.setId(id);
        instructionsPromptTextView.setText(R.string.click_the_button_to_add_semesters);
        instructionsPromptTextView.setTextSize((float)width);
        instructionsPromptTextView.setVisibility(View.VISIBLE);
        instructionsPromptTextView.setBackgroundColor(Color.BLACK);
        relativeLayout.addView(instructionsPromptTextView);

        /*
        if(id == 0){
            instructionsPromptTextView.setVisibility(View.INVISIBLE);
        }*/

    }

    public void onFloatActionButtonClick(View view) {
        if (counter < 8) {
            addSemesterButton(counter);

            counter++;
            setOnLongClickListenerForSemesterButton();

            // Required to show delete option
            updateOptionMenu(); 

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

        // Will never be called because counter == 0 will be consumed by first if condition 
        /*
        else if (counter == 0){
            addTextView(counter); // Move it to onCreate()
        }*/
    }

    public void updateOptionMenu() {
        if (counter > 0) 
            item.setVisible(true);
        else
            item.setVisible(false);    
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);

        itemDelete = menu.findItem(R.id.delete);

        // Required to hide delete option when app starts first
        itemDelete.setVisible(false); 

        return true;
    }

    @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;
                                updateOptionMenu(); // Required to hide option item when all views are removed
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        })
                        .show();
                return true;
            }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        savedInstanceState.putInt("counter", counter);
        super.onSaveInstanceState(savedInstanceState);
    }

    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--;
                                updateOptionMenu(); // Required to hide delete item if this button is last button to be removed
                            }
                        });
                        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;
            }
        });
    }
}

Hope this will help~ 希望这会有所帮助〜

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM