我正在膨胀菜单并尝试通过以下方式找到其中一个菜单项的 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/