Singee Singee - 3 months ago 13
Android Question

How to get ImageView ID from inflater in Android

I'm using an inflater to show a popup setting menu made by me. It's composed by some images and buttons. After complete XML layout I'm started to code it, it opens correctly with this code:

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);

}


But now I need to get ImageViews IDs and Buttons IDs, I've used:

//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);


But when I'm starting to use this Views for example
popup_setting_1_icon.setImageResource(R.id.setting_done_icon);
I get application crash with
NullPointerException
.
I've read something like I should get pointers from inflater but I've tried to do so inside
showPopup
method but nothing. How I can solve this problem?

Answer

Initialize views in show popup method:

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);