何时使用菜单项id调用findViewById以确保它不为null?

Pio*_*ski 6 android android-menu findviewbyid

我正在给菜单充气,并试图通过以下方式查找其中一个菜单项的视图:

 @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;
 }
Run Code Online (Sandbox Code Playgroud)

在结果null中打印在Logcat中.但是如果我在调用之前添加一些延迟findViewById,它将返回正确的View对象:

@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;
}
Run Code Online (Sandbox Code Playgroud)

当然,这种解决方案非常脏,最小的延迟是未知的.有没有办法为菜单膨胀事件注册一些回调.换句话说:如何findViewById使用菜单项ID 调用以确保视图已经存在并且此调用不会返回null

Nom*_*sta 2

只需覆盖public void onPrepareOptionsMenu(Menu menu).

文档说:

每次显示菜单时,都会在显示菜单之前调用此函数。您可以使用此方法有效地启用/禁用项目或以其他方式动态修改内容。

的视图Menu是在调用后创建的onCreateOptionsMenu(Menu),这就是为什么您无法访问它的子视图。