我正在使用充气机显示由我制作的弹出设置菜单。它由一些图像和按钮组成。完成XML布局后,我开始对其进行编码,并使用以下代码正确打开它:
public void Settings_button(View view)
{
if (p != null)
showPopup(Main_activity.this, p);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
int[] location = new int[2];
ImageButton setting_button = (ImageButton) findViewById(R.id.settings_button);
// Get the x, y location and store it in the location[] array
// location[0] = x, location[1] = y.
setting_button.getLocationOnScreen(location);
//Initialize the Point with x, and y positions
p = new Point();
p.x = location[0];
p.y = location[1];
}
// The method that displays the popup.
private void showPopup(final Activity context, Point p) {
Resources r = getResources();
int popupWidth = 500;
int popupHeight = 300;
// Inflate the popup_layout.xml
LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup);
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.settings_popup_layout, viewGroup);
// Creating the PopupWindow
final PopupWindow popup = new PopupWindow(context);
popup.setContentView(layout);
popup.setWidth(popupWidth);
popup.setHeight(popupHeight);
popup.setFocusable(true);
// Some offset to align the popup a bit to the right, and a bit down, relative to button's position.
int OFFSET_X = 150;
int OFFSET_Y = 30;
// Displaying the popup at the specified location, + offsets.
popup.showAtLocation(layout, Gravity.NO_GRAVITY, p.x + OFFSET_X, p.y + OFFSET_Y);
}
但是现在我需要获取ImageViews ID和Buttons ID,我已经使用了:
//In onCreate of Main_Activity
ImageView popup_setting_1_icon;
popup_setting_1_icon = (ImageView) findViewById(R.id.setting_1_icon);
Button popup_setting_1_button;
popup_setting_1_button = (Button) findViewById(R.id.setting_1_button);
但是,当我开始使用该视图作为示例时,例如
popup_setting_1_icon.setImageResource(R.id.setting_done_icon);
,我的应用程序因NullPointerException
而崩溃。我读过类似的文章,我应该从充气机获取指针,但是我尝试在
showPopup
方法中这样做,但是什么也没有。我该如何解决这个问题? 最佳答案
用show popup方法初始化视图:
ImageView popup_setting_1_icon;
popup_setting_1_icon = (ImageView)layout. findViewById(R.id.setting_1_icon);
Button popup_setting_1_button;
popup_setting_1_button = (Button)layout. findViewById(R.id.setting_1_button);
关于java - 如何从Android中的充气机获取ImageView ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35177553/