android - 何时使用菜单项 ID 调用 findViewById 以确保它不为空?

标签 android android-menu findviewbyid

我正在膨胀菜单并尝试通过以下方式找到其中一个菜单项的 View :

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

结果 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;
}

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

最佳答案

只需覆盖 public void onPrepareOptionsMenu(Menu menu)

文档说:

This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.

Menu 的 View 是在调用 onCreateOptionsMenu(Menu) 之后创建的,这就是您无法访问它的 subview 的原因。

关于android - 何时使用菜单项 ID 调用 findViewById 以确保它不为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50820535/

相关文章:

android - 是否有 eclipse 插件来生成 findViewById 调用?

android - cordova 中所有平台的通用 www 文件夹和所有文件

java - 如何在启动 Android LibGDX 项目时修复 NoClassDefFoundError?

java - 将项目添加到自定义 ListView 仅在触摸时显示新项目

android - 更改菜单 actionLayout 值?

android - 更改android中菜单项的文本大小

android - 像菜单项一样的路径 - Android

android - 我如何为 android :id? 使用 findViewById

javascript - 手机innerWidth,innerHeight vs Resolution

android - 偶尔从 (View).findViewByID 获取 null