我正在使用导航视图。由于某种原因,我无法获得菜单项的视图。它始终为空。我试过viewobserver,findViewByid,但它没有用。我需要在执行项目选择事件时获得当前菜单项位置的y coord。这可能吗?
初始化抽屉
activity.drawerIndicator.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (activity.drawerLayout.isDrawerVisible(GravityCompat.START)) {
activity.drawerLayout.closeDrawer(GravityCompat.START);
} else {
activity.drawerLayout.openDrawer(GravityCompat.START);
}
}
});
activity.drawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
@Override
public void onDrawerSlide(View view, float v) {
}
@Override
public void onDrawerOpened(View view) {
activity.closeKeyboard();
}
@Override
public void onDrawerClosed(View view) {
// your refresh code can be called from here
//activity.closeKeyboard();
}
@Override
public void onDrawerStateChanged(int i) {
}
});
初始化导航视图
public void initNavigationView() {
activity.navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Closing drawer on item click
final int itemId=menuItem.getItemId();
final ViewTreeObserver viewTreeObserver =activity.navigationView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
View menuButton = activity.findViewById(itemId);
// This could be called when the button is not there yet, so we must test for null
if (menuButton != null) {
// Found it! Do what you need with the button
int[] location = new int[2];
menuButton.getLocationInWindow(location);
SharedPreferencesController.getInstance(activity.getApplicationContext()).setTopPosition(location[1]);
// Now you can get rid of this listener
viewTreeObserver.removeGlobalOnLayoutListener(this);
}
}
});
activity.drawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
case R.id.checkin:
if (!menuItem.isChecked())
menuItem.setChecked(true);
return goToCheckinItemMenu();
case R.id.boarding_passes:
return goToBoardingPassesItemMenu(menuItem);
case R.id.flight_status:
return goToFlightStatusItemMenu(menuItem);
case R.id.timetable:
return goToTimetableItemMenu(menuItem);
case R.id.promotion:
return goToPromotionItemMenu(menuItem);
//case R.id.reccomend_app:
// return goToReccomendAppItemMenu();
case R.id.about_app:
return goToAboutAppItemMenu(menuItem);
case R.id.contact_us:
return goToContactUsItemMenu(menuItem);
case R.id.settings:
return goToSettingsItemMenu(menuItem);
case R.id.data_protection:
return goToDataProtectionItemMenu(menuItem);
case R.id.checkin_info:
return goToCheckinInfoItemMenu(menuItem);
case R.id.panorama:
return goToPanoramaCLubItemMenu();
default:
Toast.makeText(activity.getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
return true;
}
}
}
);
}
如您所见,我试图使用TreeObserver在屏幕上获取menuItem的当前位置。我知道观察者在事情发生后会起作用,这意味着它在被叫之后无法正常工作。但无论如何,menuButton视图始终为null