How can we use menu items outside onOptionItemSelected like in onCreate()

﹥>﹥吖頭↗ 提交于 2020-01-04 04:46:07

问题


I am facing a problem in getting a reference to a menu item outside onOptionsItemSelected() method. I want that part of code to be executed as soon as my Activity is created, so I am trying to use that menu item in onCreate() but it is always returning null. Any help would be greatly appreciated.

I am trying the following code:

private Menu menu;

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

 updateMenu();

}

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_sub_task_detail, menu);

        this.menu = menu;
        menuItem = menu.findItem(R.id.markComplete);

        return true;

    }

    public void updateMenu(){

        menuItem = menu.findItem(R.id.markComplete);
        SharedPreferences sharedPreferences1 = getSharedPreferences("StatusValue", Context.MODE_PRIVATE);
        int count2 = sharedPreferences1.getInt("status", 0);
        if (count2 != 0){
          menuItem.setEnabled(false);

        }

        else {
            menuItem.setEnabled(true);
        }




    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.

        SharedPreferences sharedPreferences1 = getSharedPreferences("StatusValue", Context.MODE_PRIVATE);
        int count2 = sharedPreferences1.getInt("status", 0);
        if (count2 != 0){

            menuItem.setEnabled(false);
        }

          int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        if (id == R.id.markComplete) {


            SQLiteDataBaseAdapter db = new SQLiteDataBaseAdapter(this);
          String taskname = task_name.getText().toString();
           int subTaskNumber1 = db.getSubTaskUID(taskname);
            int taskNumber = db.getTaskUID(position1);
            Log.d("Pana", "The value of Sub Task Number is " +subTaskNumber1);
            Long result = db.updateUserTable(1, subTaskNumber1, taskNumber);
            //Toast.makeText(this, "The value of result is " + result, Toast.LENGTH_LONG).show();

            // getting current Date and Time
            Calendar c = Calendar.getInstance();
            SimpleDateFormat df1 = new SimpleDateFormat("MM/dd/yyyy HH:mm");
            String formattedDate = df1.format(c.getTime());
            // formattedDate have current date/time
            Log.d("Pana", "Formatted Date is " + formattedDate);


            String[] dateTimeSplit = formattedDate.split(" ");
            String currDate = dateTimeSplit[0];
            String currTime = dateTimeSplit[1];

            subTask = db.getSubTask(position);
            String subTaskName = subTask.getSub_Task_Name();

           int UID = db.getSubTaskUID(subTaskName);


            db.updateEstCompTimeDateSubTask(UID, currTime, currDate);

            String[] actTimeDate = db.getActTimeDateSubTask(taskname);

            String actTime = actTimeDate[0];
            String actDate = actTimeDate[1];
            act_compDate.setText(actTime);
            act_compTime.setText(actDate);



            int count = db.checkOtherSubTask(taskNumber);

            if (count == 0){

                Toast.makeText(this, "There are no active Sub Tasks for the corresponding Task. Please create a new Sub Task or mark the corresponding task as completed", Toast.LENGTH_LONG).show();
            }

            int count1 = db.getStatus(taskNumber, subTaskNumber1);

            SharedPreferences sharedPreferences = getSharedPreferences("StatusValue", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putInt("status", count1);
            editor.commit();

            if (count1 != 0) {
                item.setEnabled(false);
            }


        }

        return super.onOptionsItemSelected(item);
    }

Here I want to set the item with id R.id.markComplete in my onCreate method, but I am unable to get a reference to that item. All suggestions are welcome. Thanks in advance.


回答1:


Its not advisable to do what you want. While you can create a class field

private Menu menu;

and capture its value in onCreateOptionsMenu()

this.menu = menu;

it is known that the value of menu abruptly becomes null at certain points in the Activity / Fragment life-cycle. Hence you are advised to do everything you want with menu in the onCreateOptionsMenu(), onPrepareOptionsMenu() and onOptionsItemSelected() methods. Those methods are the right place to do that.

References:

1. Menus.

2. Options Menu Tutorial.



来源:https://stackoverflow.com/questions/29433550/how-can-we-use-menu-items-outside-onoptionitemselected-like-in-oncreate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!