Thursday, 26 July 2018

When to call findViewById with menu item id to ensure it is not null?

I'm inflating the menu and trying to find the view of one of the menu items in the following way:

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

     // will print `null`
     Log.i("TAG", String.valueOf(findViewById(R.id.action_hello)));
     return true;
 }

In the result null is printed in Logcat. However if I add some delay before calling findViewById, it returns correct View object:

@Override
public boolean onCreateOptionsMenu(final Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(final Void... voids) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(final Void aVoid) {
            // will print correctly android.support.v7.view.menu.ActionMenuItemView...
            Log.i("TAG", String.valueOf(findViewById(R.id.action_hello)));
        }
    }.execute();
    return true;
}

Of course this solution is very dirty and the minimal delay is unknown. Is there a way to register some callback for the menu inflated event. In other words: how can I call findViewById with the menu item id to be sure that the view is already there and this call won't return null?



from When to call findViewById with menu item id to ensure it is not null?

No comments:

Post a Comment